[英]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')
the code is supposed to read the txt file line by line and determine if the 'word' variable is exactly equal to one of those lines.该代码应该逐行读取 txt 文件并确定“word”变量是否正好等于其中一行。 the problem is that whenever it runs, the variable doesn't have to be exactly equal.
问题是无论何时运行,变量都不必完全相等。 for example, say one of the lines is 'free', and I search 'e', it will still pop up that it's in the txt file.
例如,假设其中一行是“免费”,我搜索“e”,它仍然会弹出它在 txt 文件中。 thanks in advance.
提前致谢。
in
, as it says, checks if the object is in another object. That includes a character in a string. in
正如它所说,检查 object 是否在另一个 object 中。这包括字符串中的一个字符。 You should use ==
for exactly equals*.您应该使用
==
表示完全等于*。
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
*. *。 well, not exactly.
好吧,不完全是。 It's kinda hard to explain.
有点难以解释。
==
returns True
if the values of the object are equal, but that doesn't mean they have the same type. ==
如果 object 的值相等,则返回True
,但这并不意味着它们具有相同的类型。 If you want to check if they are the same type, use is
.如果要检查它们是否是同一类型,请使用
is
。
I'd appreciate it if someone smarter than me edits my question clarifying my ramblings above.如果比我聪明的人编辑我的问题来澄清我上面的胡言乱语,我将不胜感激。
The problem in your code is this line:您的代码中的问题是这一行:
if string_to_search in line:
which will be true if the string occurs anywhere in line
.如果字符串出现在
line
中的任何位置,则为真。 It doesn't match against a whole word.它与整个单词不匹配。 I think that's what you want to do?
我想这就是你想要做的?
What you can do is break up each line into a list of words.您可以做的是将每一行分解成一个单词列表。 The
split()
method of the string class can do that.字符串 class 的
split()
方法可以做到这一点。 If your line contains punctuation characters you would have remove them too for comparison with your search string;如果您的行包含标点符号,您也可以删除它们以便与您的搜索字符串进行比较; for that you can use the string's
strip()
method.为此,您可以使用字符串的
strip()
方法。 Putting it all together your check()
function becomes:把它们放在一起你的
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.