我有2列的excel文件,如下所示。我想检查列名“ CODE1”中的单元格内容是否存在于从屏幕输入的字符串中,然后返回的结果是列名“ RESULT”
import pandas as pd
import getpass
import random
path_to_csv_file = 'C:\\names.xlsx'
code_names_dataframe = pd.read_excel(path_to_csv_file)
code_names_dictionary = code_names_dataframe.to_dict(orient='records')
user_response = input()
user_response=user_response.lower()
while True:
name = None
username = user_response
for code_name in code_names_dictionary:
if username.contains(code_name['CODE1']).any():
name = code_name['RESULT']
if name is not None:
break
else:
print('Not Correct')
break
print(name)
Excel格式如下:
CODE1 RESULT
excel OK. Excel
apple OK. Apple
我想当用户在屏幕上输入字符串为“我想接收一个苹果”时...那么结果将在屏幕上返回“确定”。苹果'
当我运行代码时,它显示如下错误:
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\Chatbot - ReadData\ExcelCSV.py", line 58, in <module>
mainmenu()
File "C:\Users\Administrator\Desktop\Chatbot - ReadData\ExcelCSV.py", line 49, in mainmenu
if username.contains(code_name['CODE1']).any():
AttributeError: 'str' object has no attribute 'contains'
请帮我。
您可以将文本分成单词列表,然后可以使用 isin()
import pandas as pd
df = pd.DataFrame({
'CODE': ['excel', 'apple'],
'RESULT':['OK. Excel', 'OK. Apple']
})
text = 'I want to receive an apple'.lower()
words = text.split(' ')
mask = df['CODE'].isin(words)
print( mask )
print( df[ mask ] )
if mask.any():
name = df[mask]['RESULT'].iloc[0]
else:
name = None
print('Name:', name)
结果
# mask
0 False
1 True
Name: CODE, dtype: bool
# df[mask]
CODE RESULT
1 apple OK. Apple
Name: OK. Apple
编辑:其他方法
mask = df['CODE'].apply(lambda x: x.lower() in text.lower())
码
import pandas as pd
df = pd.DataFrame({
'CODE': ['excel file', 'apple'],
'RESULT':['OK. Excel', 'OK. Apple']
})
text = 'I have excel file on the PC'
mask = df['CODE'].apply(lambda x: x.lower() in text.lower())
print( mask )
print( df[ mask ] )
if mask.any():
name = df[mask]['RESULT'].iloc[0]
else:
name = None
print('Name:', name)
结果
# mask
0 True
1 False
Name: CODE, dtype: bool
# df[mask]
CODE RESULT
0 excel file OK. Excel
Name: OK. Excel
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句