2016-04-15 53 views
-1

我创建了以下程序并导入了一个CSV文件,其中包含与常见手机问题相关的单词。我的问题是,它会选择“粉碎”,但不会因为逗号而选择“粉碎”。Python中的CSV文件没有给出确切的结果

所以,我的问题是,我怎样才能让它在没有逗号的情况下阅读这个词,而不是给我任何错误或任何东西?

任何帮助将不胜感激:)

import csv 

screen_list = {} 

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

print("Welcome to the troubleshooting program. Here we will help you solve your problems which you are having with your phone. Let's get started: ") 

what_issue = input("What is the issue with your phone?: ") 
what_issue = what_issue.split(' ') 

results = [(solution, screen_list[solution]) for solution in what_issue if solution in screen_list] 


if len(results) > 6: 
    print('Please only insert a maximum of 6 problems at once. ') 
else: 
    for solution, problems in results: 
     print('As you mentioned the word in your sentence which is: {}, the possible outcome solution for your problem is: {}'.format(solution, problems)) 

exit_program = input("Type 0 and press ENTER to exit/switch off the program.") 
+0

请自己展示你自己的尝试,并解释它为什么不起作用。 – martineau

回答

1

你的问题是,当你splitwhat_issue字符串。最好的解决办法是在这里使用正则表达式:

>>> import re 
>>> what_issue = "My screen is smashed, usb does not charge" 
>>> what_issue.split(' ') 
['My', 'screen', 'is', 'smashed,', 'usb', 'does', 'not', 'charge'] 

>>> print re.findall(r"[\w']+", what_issue) 
['My', 'screen', 'is', 'smashed', 'usb', 'does', 'not', 'charge'] 
0

您所遇到的计算机科学课题称为tokenization

它看起来像你想从用户输入中删除所有非字母字符。一个简单的方法是使用Python的re库,它支持正则表达式。

下面是使用re做到这一点的例子:

import re 
regex = re.compile('[^a-zA-Z]') 
regex.sub('', some_string) 

首先,我们创建匹配字母的所有字符正则表达式。然后我们使用这个正则表达式来替换some_string中的所有匹配字符,并将其从字符串中删除。

做同样的事情的一个快速和肮脏的方法是使用属于所有Python字符串的​​方法来过滤不需要的字符。

some_string = ''.join([char for char in some_string if char.isAlpha()]) 

这里我们制作一个只包含some_string的字母字符的列表。然后我们一起创建一个新字符串,我们将其分配给some_string

相关问题