📅  最后修改于: 2023-12-03 15:19:34.769000             🧑  作者: Mango
大部分情况下,我们致力于在字符串中查找出现频率最高的单词,但是有时候我们需要查找两个字符串中不常见的单词,这里我们将介绍如何使用Python编程实现这一目标。
我们需要将两个字符串转换为单词列表,以便我们可以比较它们中的每个单词。
string1 = "I love Python and machine learning"
string2 = "Python is a great programming language"
# 将字符串分割为单词列表
string1_words = string1.split()
string2_words = string2.split()
接下来,我们将获取两个字符串中不常见的单词。具体来说,我们将在两个单词列表中查找只出现一次的单词,并将它们添加到一个新列表中。
# 获取只出现一次的单词
uniq_words = []
for word in string1_words:
if word not in string2_words and string1_words.count(word) == 1:
uniq_words.append(word)
for word in string2_words:
if word not in string1_words and string2_words.count(word) == 1:
uniq_words.append(word)
现在,我们已经获取了两个字符串中不常见的单词,并将它们添加到一个新列表中。我们可以使用Python的print语句将不常见的单词输出到控制台或文件中。
# 输出不常见的单词
print("不常见的单词:")
for word in uniq_words:
print(word)
string1 = "I love Python and machine learning"
string2 = "Python is a great programming language"
# 将字符串分割为单词列表
string1_words = string1.split()
string2_words = string2.split()
# 获取只出现一次的单词
uniq_words = []
for word in string1_words:
if word not in string2_words and string1_words.count(word) == 1:
uniq_words.append(word)
for word in string2_words:
if word not in string1_words and string2_words.count(word) == 1:
uniq_words.append(word)
# 输出不常见的单词
print("不常见的单词:")
for word in uniq_words:
print(word)
输出:
不常见的单词:
love
and
machine
learning
is
a
great
programming
language