[英]Python - Dictionary - If loop variable not changing
项目即将把短格式转换成长描述并从 csv 文件中读取
示例:用户输入 LOL,然后应响应“笑声”
期望:直到用户输入错误的关键字计算机一直要求输入简短的格式和系统回答它是来自 CSV 文件的详细描述我将 CSV 文件的每一行视为字典并分解为使用的键和值逻辑:-同时使用,它一直在询问,直到短列没有找到空间,空单元格。 但问题是在 IF 循环中显示成功的第一次尝试比较没有发生之后,因为 readitems['short'] 没有在每个周期更新
AlisonList.csv 值为:
short,long
lol,laugh of laughter
u, you
wid, with
import csv
from lib2to3.fixer_util import Newline
from pip._vendor.distlib.util import CSVReader
from _overlapped import NULL
READ = "r"
WRITE = 'w'
APPEND = 'a'
# Reading the CSV file and converted into Dictionary
with open ("AlisonList.csv", READ) as csv_file:
readlist = csv.DictReader(csv_file)
# Reading the short description and showing results
for readitems in readlist:
readitems ['short'] == ' '
while readitems['short'] !='' :
# Taking input of short description
smsLang = str(input("Enter SMS Language : "))
if smsLang == readitems['short']:
print(readitems['short'], ("---Means---"), readitems['long'])
else:
break
尝试这个:
import csv
READ = "r"
WRITE = 'w'
APPEND = 'a'
# Reading the CSV file and converted into Dictionary
with open ("AlisonList.csv", READ) as csv_file:
readlist = csv.DictReader(csv_file)
word_lookup = { x['short'].strip() : x['long'].strip() for x in readlist }
while True:
# Taking input of short description
smsLang = str(input("Enter SMS Language : ")).lower()
normalWord = word_lookup.get(smsLang.lower())
if normalWord is not None:
print(f"{smsLang} ---Means--- {normalWord}")
else:
print(f"Sorry, '{smsLang}' is not in my dictionary.")
示例输出:
Enter SMS Language : lol
lol ---Means--- laugh of laughter
Enter SMS Language : u
u ---Means--- you
Enter SMS Language : wid
wid ---Means--- with
Enter SMS Language : something that won't be in the dictionary
Sorry, 'something that won't be in the dictionary' is not in my dictionary.
基本上,我们从 csv 文件编译一个字典,使用短词作为关键字,使用长词作为项目。 这允许我们在循环中调用word_lookup.get(smsLang)
来查找更长的版本。 如果这样的键不存在,我们会得到None
的结果,因此一个简单的 if 语句可以处理不再存在版本的情况。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.