[英]How to check if a variable is the same as a line in a txt file - python
def check(file_name, string_to_search):
with open(file_name, 'r') as read_obj:
for line in read_obj:
if string_to_search in line:
return True
return False
while True:
word = input('Is the word positive? | ')
if check('positivewords.txt', word):
print('Word is positive')
elif check('negativewords.txt', word):
print('Word is negative')
else:
print('Word not in database')
该代码应该逐行读取 txt 文件并确定“word”变量是否正好等于其中一行。 问题是无论何时运行,变量都不必完全相等。 例如,假设其中一行是“免费”,我搜索“e”,它仍然会弹出它在 txt 文件中。 提前致谢。
in
正如它所说,检查 object 是否在另一个 object 中。这包括字符串中的一个字符。 您应该使用==
表示完全等于*。
def check(file_name, string_to_search):
with open(file_name, 'r') as read_obj:
for line in read_obj:
if string_to_search.lower() == line.lower(): # <-- Changed in to == and made them lower
return True
return False
*。 好吧,不完全是。 有点难以解释。 ==
如果 object 的值相等,则返回True
,但这并不意味着它们具有相同的类型。 如果要检查它们是否是同一类型,请使用is
。
如果比我聪明的人编辑我的问题来澄清我上面的胡言乱语,我将不胜感激。
您的代码中的问题是这一行:
if string_to_search in line:
如果字符串出现在line
中的任何位置,则为真。 它与整个单词不匹配。 我想这就是你想要做的?
您可以做的是将每一行分解成一个单词列表。 字符串 class 的split()
方法可以做到这一点。 如果您的行包含标点符号,您也可以删除它们以便与您的搜索字符串进行比较; 为此,您可以使用字符串的strip()
方法。 把它们放在一起你的check()
function 变成:
import string
def check(file_name, string_to_search):
with open(file_name, 'r') as read_obj:
for line in read_obj:
#List of words (without punctuation)
words = [word.strip(string.punctuation) for word in line.split()]
if string_to_search in words:
return True
return False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.