检查单元格内容是否存在于屏幕输入的字符串中 - Python Pandas

我有一个包含2列的excel文件,如下所示。我想检查列名“CODE1”中的单元格内容是否存在于从屏幕输入的字符串中。然后在屏幕上返回结果是列名称“结果”


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

我想当用户在屏幕上输入字符串为“我想收到一个苹果”...然后结果将在屏幕上返回是“OK. 苹果”


当我运行代码时,它显示错误如下:


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'


三国纷争
浏览 85回答 1
1回答

慕容森

您可以将文本拆分为单词列表,然后可以使用isin()import pandas as pddf = pd.DataFrame({&nbsp; &nbsp; &nbsp; &nbsp; 'CODE': ['excel', 'apple'],&nbsp; &nbsp; &nbsp; &nbsp; '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():&nbsp; &nbsp; name = df[mask]['RESULT'].iloc[0]else:&nbsp; &nbsp; name = Noneprint('Name:', name)&nbsp;&nbsp;结果# mask0&nbsp; &nbsp; False1&nbsp; &nbsp; &nbsp;TrueName: CODE, dtype: bool# df[mask]&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; CODE&nbsp; &nbsp; &nbsp;RESULT1&nbsp; apple&nbsp; OK. AppleName: OK. Apple编辑:其他方法mask = df['CODE'].apply(lambda x: x.lower() in text.lower())法典import pandas as pddf = pd.DataFrame({&nbsp; &nbsp; &nbsp; &nbsp; 'CODE': ['excel file', 'apple'],&nbsp; &nbsp; &nbsp; &nbsp; '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():&nbsp; &nbsp; name = df[mask]['RESULT'].iloc[0]else:&nbsp; &nbsp; name = Noneprint('Name:', name)&nbsp;结果# mask0&nbsp; &nbsp; &nbsp;True1&nbsp; &nbsp; FalseName: CODE, dtype: bool# df[mask]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;CODE&nbsp; &nbsp; &nbsp;RESULT0&nbsp; excel file&nbsp; OK. ExcelName: OK. Excel
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python