My CSV dataset Scrips.csv 是这样的:
Code,Id
500002,ABB
500003,AEGISLOG
500004,TPAEC
500005,AKARLAMIN
500006,ALPHADR
500008,AMARAJABAT
500009,AMBALALSA
500010,HDFC
500011,AMRTMIL-BDM
500012,ANDHRAPET
500013,ANSALAPI
我想以字符串的形式获取用户输入并将其与"Id"列匹配。如果没有完全匹配项,我还希望查看最接近的匹配项,并要求用户输入其中一个匹配项。匹配后,我希望"代码"对应于返回的 Id。
我想要的输出是:
Enter the Id: ABB
500002
使用以下代码我无法到达任何地方:
import pandas as pd
from difflib import get_close_matches
df = pd.read_csv(r"C:UsersfcBSE ScraperScrips.csv", index_col=0)
for row in df.index:
if row == "ABB":
print("True")
elif len(get_close_matches(row, df.index())) > 0:
print("Did you mean %s instead?" % get_close_matches(row, df.index())[0])
else:
print("No match found. Please try again.")
您可以将自定义函数与Id
列转换为index
并f-string
s:
def func(df, x):
df = df.set_index('Id')
m = df.index == x
if m.sum() > 0:
a = df.loc[x, 'Code']
return f'Exact match: {a}'
else:
val = get_close_matches(x, df.index)
if len(val) > 0:
a = df.loc[val[0], 'Code']
return f'Did you mean {val} instead for match {a}? '
else:
return "No match found. Please try again."
print (func(df, 'ABB'))
Exact match: 500002
print (func(df, 'ABB1'))
Did you mean ABB instead for match 500002?
print (func(df, 'something'))
No match found. Please try again.
我不知道你认为的类似id的标准是什么。
但我创建了一些这样的逻辑:
def get_close_matches(string):
global df
get_sr2 = df['Id'][df['Id'].str.startswith(string[:2])]
if len(get_sr2) !=0:
return get_sr2.tolist()
else:
return ''
while True:
get_id = input('Enter the Id : ')
get_sr = df['Code'][df['Id'].isin([get_id])]
if len(get_sr) != 0:
print(get_sr.iloc[0])
break
elif get_close_matches(get_id):
print("Do you mean one of the following?")
print(get_close_matches(get_id),'n')
continue
else:
print("No match found. Please try again.")
continue
Enter the Id : AB
Do you mean one of the following?
['ABB']
Enter the Id : ABB
500002
- 输入字符串。
- 如果存在完全匹配项,则返回代码。如果存在以输入字符开头的 id,则返回一个列表。
- 如果在步骤 2 中未执行任何操作,则打印一些文本。