Python中的CSV文件没有给出确切的结果

时间:2016-04-15 07:08:57

标签: python csv

我创建了以下程序并导入了一个CSV文件,其中包含与常见手机问题相关的字词。我的问题是,它会选择"粉碎"但是它不会被淘汰,#34;捣碎,"因为逗号。

所以,我的问题是,如何让它在没有逗号的情况下阅读单词并且不给我任何错误或任何其他内容?

任何帮助将不胜感激:)

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.")

2 个答案:

答案 0 :(得分:1)

您的问题是split what_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']

答案 1 :(得分:0)

您在计算机科学中遇到了一个名为tokenization的主题。

您似乎想要从用户输入中删除所有非字母字符。一种简单的方法是使用Python的re库,它支持正则表达式。

以下是使用re执行此操作的示例:

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

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

执行相同操作的快速方法是使用属于所有Python字符串的isAlpha方法来过滤掉不需要的字符。

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

这里我们列出一个仅包含some_string字母字符的列表。然后我们将它们连接在一起以创建一个新字符串,我们将其分配给some_string

相关问题