Numpy Python-Can';无法匹配文件中的字符串
我有这个Numpy Python-Can';无法匹配文件中的字符串,numpy,Numpy,我有这个textfile.txt: i car air me 字典的定义如下: dictionary = {"me":3, "you":4, "else": 10, "i":2} 我正在寻找一种方法,以可概括的方式从字典中删除textfile.txt中的单词(我在这里使用循环),我的尝试: words_to_delete = open("textfile.txt", "r"
textfile.txt
:
i
car
air
me
字典的定义如下:
dictionary = {"me":3, "you":4, "else": 10, "i":2}
我正在寻找一种方法,以可概括的方式从字典中删除textfile.txt中的单词(我在这里使用循环),我的尝试:
words_to_delete = open("textfile.txt", "r")
for i in words_to_delete.readlines():
del dictionary[i]
# Output: KeyError: 'i\n'
更进一步说,我认为是因为:
for i in words_to_delete.readlines():
print(i == "me")
# Output: False, False, False, False
为什么循环中的值与textfile.txt
中的值不可比较
如果我运行这个:
for i in words_to_delete.readlines():
print(type(i))
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
for i in words\u to\u delete.readlines():
印刷品(第(i)类)
它是一个字符串,那么为什么字典中的字符串
i
和me
在与暴力写入的字符串进行比较时返回False
?您需要修剪空白(或者在本例中为新行\n
。在末尾有\n
的字符串上调用strip方法。(如s.strip())我不明白。文本文件没有任何空格。当您阅读这些行时,末尾的换行符会保留下来。换行符是像tab和space这样的空格。您是否看到keyerror中的\n
“I\n”和“I”
明显不同