用户输入输入中的句子,Python选择关键字并从CSV文件中获取

时间:2016-02-02 08:25:04

标签: python csv

我有一项任务是使用CSV文件创建代码。我必须创建一个代码,在运行它之后,用户必须在一个句子中输入答案,然后Python必须从句子中挑出关键字并从CSV文件中交叉引用并给用户一个答案。 我创建了一个代码,询问:

您想知道哪些游戏的价格?

用户必须写一个可能会说:

的答案

我想知道价格的游戏是:FarCry4 GTA 5

然后,Python必须选择 FarCry4 GTA5 这两个词。然后它必须在导入CSV文件后告诉游戏的价格,但我不能这样做,因为Python选择Python中的每个单词并告诉价格。请帮忙。

CODE:

import csv

games = []#subjects
howmuchitcosts = []#teachers

with open('gamesandprices.csv') as csvfile:
    readCSV = csv.reader(csvfile)

    for row in readCSV:
        games.append(row[0])
        howmuchitcosts.append(row[1])


what_game = input("Which game(s) would you like to find out the price of?: ")

what_game = what_game.split(' ')

if len(what_game) > 6:
    print("Too many games. Only type in 6 games.")

for one_game in what_game:

    theprice = []
    gamedex = 0

    while True:

        try:
            gamedex = games.index(one_game, gamedex)
        except:
            break 

        theprice.append(howmuchitcosts[gamedex])

        gamedex += 1 

    theprice = ', '.join(theprice)

    print("The price of", one_game, "is", theprice)

P.S:我在另一个主题的StackOverflow中提到了另一个问题的代码。

当我输入以下句子时:     我想知道GTA5和FarCry4的价格

当我按 ENTER 时,会出现这种情况:

Too many games. Only type in 6 games.
The price of I is 
The price of want is 
The price of to is 
The price of know is 
The price of the is 
The price of price is 
The price of of is 
The price of GTA5 is £30.99
The price of and is 
The price of FarCry4 is £40.99

但是我希望python只选择GTA5和FarCry4并告诉这些游戏的价格,而不是整个句子。

这是来自另一个主题,因为他正在处理相同的代码:)

1 个答案:

答案 0 :(得分:1)

更改读取csv的代码以生成字典,然后只需从输入中查找单词。如果单词在字典中,则表示您对该游戏有价格;因此只打印输出:

import csv

price_list = {} # this is an empty dictionary

with open('gamesandprices.csv') as csvfile:
    readCSV = csv.reader(csvfile)
    for row in readCSV:
        price_list[row[0]] = row[1]

what_game = input("Which game(s) would you like to find out the price of?: ")
what_game = what_game.split(' ')

# Now what we want to do, is for each word in the input, check if it
# exists in our dictionary. If it does exist, it must be the name of
# a game, so we need to know its price.

# We also want to make sure we limit the number of games in one
# request to 6 games. To find out how many games the person entered,
# lets filter all the words and collect those words (and prices)
# that are games in a list.

# The long way of writing this is:
# results = [] - this is an empty list
# for word in what_game:
#    if word in price_list: 
#        results.append(word, price_list[word])

results = [(game, price_list[game]) for game in what_game if game in price_list]

if len(results) > 6:
    print('Please ask prices for a maximum of 6 games')
else:
    for game, price in results:
        print('The price of {} is {}'.format(game, price))