【问题标题】:Python - Dictionary - If loop variable not changingPython - 字典 - 如果循环变量没有改变
【发布时间】:2020-01-01 07:37:28
【问题描述】:

项目即将将短形式转换为长描述并从 csv 文件中读取

示例:用户输入 LOL,然后它应该响应“Laugh of Laughter”

期望:直到用户输入错误的关键字计算机一直要求输入短格式并且系统回答它来自 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

【问题讨论】:

  • 感谢 Ed Ward。真的谢谢

标签: python loops dictionary if-statement


【解决方案1】:

试试这个:

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) 来查找更长的版本。如果这样的key不存在,我们会得到None的结果,所以一个简单的if语句就可以处理没有版本的情况。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    相关资源
    最近更新 更多