【发布时间】:2018-10-12 20:34:31
【问题描述】:
我有这段代码使用假日期(如下),它工作正常:
exg = ["I love apple.",
"there are lots of health benefits of apple.",
"apple is especially hight in Vitamin C,",
"alos provide Vitamin A as a powerful antioxidant!"]
fruit_list = ["pear", "banana", "mongo", "blueberry", "kiwi", "apple", "orange"]
for j in range(0, len(exg)):
sentence = exg[j]
if any(word in sentence for word in fruit_list):
print(sentence)
输出如下:只显示fruit_list中包含单词的句子。
I love apple.
there are lots of health benefits of apple.
apple is especially hight in Vitamin C,
然后我将fruit_list更改为我的真实数据(real_list),真实数据来自excel表格中的一列。读取数据代码如下:
import pandas as pd
data = pd.read_excel('C:/Users/my/Desktop/my_list.xlsx', 'Sheet1')
real_list = data['name'].tolist()
但是我的代码已经不行了,错误如下图:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-101-5a886e386099> in <module>()
7 for j in range(0, len(exg)):
8 sentence = exg[j]
----> 9 if any(word in sentence for word in real_list):
10 print(sentence)
<ipython-input-101-5a886e386099> in <genexpr>(.0)
7 for j in range(0, len(exg)):
8 sentence = exg[j]
----> 9 if any(word in sentence for word in real_list):
10 print(sentence)
TypeError: 'in <string>' requires string as left operand, not float
我确定问题出在 real_list 上。而且我无法在此处显示 real_list(希望您能理解),但是之前有人遇到过此错误消息吗?知道可能是什么原因吗?请发送帮助。非常感谢!!
【问题讨论】:
-
我相信它也是。但我很想看看。当甚至没有给出重现问题的方法时,诊断问题并不容易。
-
您好,感谢您的评论。抱歉,我无法向您展示 real_list。如果有帮助,real_list 是产品名称列表,因此可能会有标点符号(例如 &、-、(、)、空格等)。该列表包含 700 多个元素。有帮助吗?
-
@S.J 你能确认你的
real_list只包含字符串而不包含任何十进制数字(浮点数)吗? -
@S.J 您应该对您的列表进行二进制搜索以缩小可能导致悲伤的项目,然后将内容隐藏为一个非私有字符串,如果您希望获得任何帮助,您可以与我们分享问题。
-
是的,可能它们不是字符串,可能其中一些值被转换为 None 或数字,您可以尝试在 any 调用中将单词转换为字符串
if any(str(word) in sentence for word in fruit_list):
标签: string python-3.x loops