Python 字符串中的关键字搜索
我正在制作一个简单的关键字识别程序,我有一个Python 字符串中的关键字搜索,python,string,list,Python,String,List,我正在制作一个简单的关键字识别程序,我有一个txt文件,每个单词都在新行中。我以列表的形式打开,然后检查句子中的每个关键字,稍后我将从数据库中打开 到目前为止,我得到了这个错误: TypeError: 'in <string>' requires string as left operand, not list 你这里有一个简单的打字错误。您试图从words.txt文件中检查每个word,但在if语句中使用了结果。因此出现了错误;Python说“我希望这个变量包含一个字符串,但实际
txt
文件,每个单词都在新行中。我以列表的形式打开,然后检查句子中的每个关键字,稍后我将从数据库中打开
到目前为止,我得到了这个错误:
TypeError: 'in <string>' requires string as left operand, not list
你这里有一个简单的打字错误。您试图从
words.txt
文件中检查每个word
,但在if
语句中使用了结果。因此出现了错误;Python说“我希望这个变量包含一个字符串,但实际上它是一个列表。”更改第二个for
循环:
for word in results:
if word in all_texts:
x += 1
我已在下面的完整程序中将变量重命名为更具描述性的变量:
word_list = []
with open('words.txt') as inputfile:
for line in inputfile:
word_list.append(line.strip())
source_text = 'vistumšākā zaudēt zilumi nāve'
source_words = source_text.split()
count = 0
for word in word_list:
if word in source_words:
count += 1
print count
你这里有一个简单的打字错误。您试图从words.txt
文件中检查每个word
,但在if
语句中使用了结果。因此出现了错误;Python说“我希望这个变量包含一个字符串,但实际上它是一个列表。”更改第二个for
循环:
for word in results:
if word in all_texts:
x += 1
我已在下面的完整程序中将变量重命名为更具描述性的变量:
word_list = []
with open('words.txt') as inputfile:
for line in inputfile:
word_list.append(line.strip())
source_text = 'vistumšākā zaudēt zilumi nāve'
source_words = source_text.split()
count = 0
for word in word_list:
if word in source_words:
count += 1
print count