2016-04-15 49 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

相關問題