[英]How to check if line in text file equals to a specific string?
I'm trying to extract lines from a text file, and make them keys for a new dictionary. 我正在尝试从文本文件中提取行,并使其成为新词典的键。 So far, I've done this: 到目前为止,我已经做到了:
file = open(FileName, 'r')
dictionary = {}
for line in file:
if line == ("Red" or "Yellow" or "Blue"):
dictionary[line] = '' # And then I'll edit this empty string later.
return dictionary
file.close()
I feel like the "if line == ..." part isn't correct, or maybe I haven't read the file correctly? 我感觉“ if line == ...”部分不正确,或者我没有正确读取文件? It isn't working. 它不起作用。
Can someone point me in the right direction, without giving a straight answer? 有人能在没有给出正确答案的情况下指出我正确的方向吗? Thank you for reading through this! 感谢您阅读本文! I appreciate it. 我很感激。
Your feelings are correct. 你的感觉是正确的。 You see, Python's if statements do not work like an English setence. 您会发现,Python的if语句不能像英语设置那样工作。 The second part of your if statement: ("Red" or "Yellow" or "Blue")
, is a boolean expression . if语句的第二部分:( ("Red" or "Yellow" or "Blue")
,是布尔表达式 。 The or
operator takes two values, and returns the first value which is true. or
运算符采用两个值,并返回第一个为true的值。 In this case, since any non-empty string in Python is considered true in boolean terms, then your boolean expression returns "Red". 在这种情况下,由于布尔值将Python中的任何非空字符串都视为true,因此布尔值表达式将返回“ Red”。 This means that what your if statement is really saying is: 这意味着您的if语句真正在说的是:
if line == "Red":
What you need to do is test line
against each value. 您需要做的是针对每个值测试line
。 While this could be done by going through each value and saying: if line == "Red" or line == "Blue"...
, Python was a much better way. 尽管可以通过遍历每个值并说: if line == "Red" or line == "Blue"...
,Python是一种更好的方法。 Using the in
operator you can create an iterable with all the values you want to test line
against. 使用in
运营商,您可以创建一个可迭代所有你要测试的值line
对。 Python will then test if line
is equal to any value in the iterable. 然后,Python将测试line
是否等于可迭代的任何值。 In your case, using a tuple will be fine, but if you need to test line
against many more values, you should use a set()
instead: 在您的情况下,使用元组就可以了,但是如果您需要针对更多的值测试line
,则应该使用set()
代替:
if line in ("Red", "Yellow", "Blue"):
# do stuff
One last point is that line
could contain a newline. 最后一点是该line
可以包含换行符。 You can remove the newline by using .strip()
. 您可以使用.strip()
删除换行符。 So your finally solution would be: 因此,您的最终解决方案将是:
if line.strip('\n') in ("Red", "Yellow", "Blue"):
# do stuff
Use: 采用:
if line in ("Red", "Yellow", "Blue"):
To check that your line does not contain spaces or \\n
, you can use: 要检查您的行是否不包含空格或\\n
,可以使用:
line.strip('\\n ')
instead of just line
: line.strip('\\n ')
而不是line
:
if line.strip('\n ') in ("Red", "Yellow", "Blue"):
dictionary[line.strip('\n ')] = ''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.