2016-04-15 13 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文字列です。コンピュータサイエンスの話題がtokenizationと呼ばれるあなたが遭遇した

>>> 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

:最良の解決策はここに正規表現を使用することです。

アルファベット以外のすべての文字をユーザー入力から削除したいようです。簡単な方法は、正規表現をサポートする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に割り当てます。

関連する問題