gpt4 book ai didi

python - 需要将字符串与Python文件中的行进行匹配

转载 作者:行者123 更新时间:2023-12-01 05:53:11 25 4
gpt4 key购买 nike

我第一次在这里问问题。我有一个名称文本文件,每行 1 个名称,我正在将其读入列表,然后复制该列表两次,第一次删除\n,第二次将列表小写。然后我要求用户输入搜索词,并将他们的输入转换为小写,然后搜索列表的小写版本,然后我获取匹配的索引,并使用它来显示该匹配的非小写版本将项目列表返回给用户(以便他们可以输入例如anivia 并返回Anivia)。这工作正常,但我确信我的代码很糟糕。我想要做的是为列表文件中的某些名称添加特定缩写,并接受这些缩写作为输入,但仍然显示全名。例如,用户输入“mumu”,会看到列表中有 Amumu - mumu,以引用 Amumu。我怎样才能接受这个缩写呢?还有其他情况,例如 mf 代表财富小姐或 kha 代表卡兹克。我想也许有第二个文件包含缩写列表,但这看起来很浪费,我确信有更好的方法。这是到目前为止我的错误代码:

f = open("champions.txt") #open the file
list = f.readlines() #load each line into the list
#print list
list2 = [item.rstrip('\n') for item in list] #remove trailing newlines in copy list
list3 = [item.lower() for item in list2] #make it all lowercase

print "-------\n", list2 #print the list with no newlines just to check

print "which champ" #ask user for input
value = raw_input().lower() #get the input and make it lowercase
if value in list3: #check list for value and then print back a message using that index but from the non-lowercase list
pos = list3.index(value)
print "list contains", list2[pos]
else: #if the input doesn't match an item print an error message
print "error"

一旦它按我需要的方式工作,我会将这一切放入我的主文件中的某个函数中。基本上,我想更改文本文件中的一些行以具有有效的备用缩写,并且能够接受其中的缩写,并且仍然向用户显示全名。例如,我的辅助文本文件中包含缩写的行之一包含以下行:

Kog'Maw - kogmaw, kog, km

我怎样才能简化我所拥有的并添加该功能?我不太确定从哪里开始,我对 python 和一般编程都很陌生。感谢您提供的任何帮助,抱歉帖子这么长。

最佳答案

好的,这是一个修改后的答案,假设有一个包含名称和缩写的文件,如 this 开头所示。 .

本质上,它的作用是创建一个大型查找表,将文件中的任何缩写加上小写的名称本身映射到每行开头的名称。

lookup = {}
with open("champions.txt") as f:
for line in f:
line = line.rstrip().split('-', 1)
if not line: continue # skip any blank lines

name = line[0].strip()
lookup[name.lower()] = name
if len(line) == 2: # any alternative names given?
for item in line[1].split(','):
lookup[item.strip()] = name

print 'lookup table:'
for alt_name, real_name in sorted(lookup.items()):
print '{}: {}'.format(alt_name, real_name)
print

while True:
print "which champ (Enter to quit): " # ask user for input
value = raw_input().lower() # get the input and make it lowercase
if not value: break

real_name = lookup.get(value)
if real_name:
print 'found:', value, '-->', real_name
else:
print 'error: no match for', value

关于python - 需要将字符串与Python文件中的行进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13499100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com