2017-03-02 10 views
0

私は入力文を分析して、ユーザーがその中の特定の単語を検索できるようにするためにこのコードを作成しました。しかし、私は入力文のすべての句読点が無視されるようにする方法を考え出すことはできません。 「そこに友人」という文が入力された場合、そこに「そこ」という単語が「そこ」と数えられているので、ユーザーが「そこ」を検索している場合、それは文にはない。私を助けてください。私はPythonには本当に新しいです。このコードを作成するには、文章のすべての句読点を無視しますか?

print("Please enter a sentence") 
sentence=input() 
lowersen=(sentence.lower()) 
print(lowersen) 
splitlowersen=(lowersen.split()) 
print (splitlowersen) 
print("Enter word") 
word=input() 
lword=(word.lower()) 
if lword in splitlowersen: 
    print(lword, "is in sentence") 
    for i, j in enumerate (splitlowersen): 
     if j==lword: 
      print(""+lword+"","is in position", i+1)  

if lword not in splitlowersen: 
    print (lword, "is not in sentence") 

答えて

0
print("Please enter a sentence") 
sentence=input() 
lowersen=(sentence.lower()) 
print(lowersen) 
splitlowersen=(lowersen.strip()) 
#to remove punctuations 
splitlowersen = "".join(c for c in splitlowersen if c not in ('!','.',':')) 
print("Enter word") 
word=input() 
lword=(word.lower()) 
if lword in splitlowersen: 
    print(lword, "is in sentence") 
    for i, j in enumerate (splitlowersen): 
     if j==lword: 
      print(""+lword+"","is in position", i+1) 

if lword not in splitlowersen: 
    print (lword, "is not in sentence") 

出力:

Please enter a sentence 
hello, friend 
hello, friend 
Enter word 
hello 
hello is in sentence 
+0

ありがとうございました! –

0

あなたは、すべての句読点で文字列を分割できます。

s = "This, is a line." 
f = s.split(".,!?") 
>>>> f = ["This", "is", "a", "line"] 
0

これは少し長いかもしれないが、のpython3でったらしいです。

# This will remove all non letter characters and spaces from the sentence 
sentence = ''.join(filter(lambda x: x.isalpha() or x == ' ', sentence) 
# the rest of your code will work after this. 

ここにいくつかの高度な概念があります。

フィルタ機能と機能 https://docs.python.org/3/library/functions.html#filter

ラムダが私たちのために、各文字をチェックする無名関数を作成しますから、真を返さないアイテムと発電機を返すiteribleがかかります。 https://docs.python.org/3/reference/expressions.html#lambda

x.isalpha()は、問題の文字が実際に文字であることを確認します。 の後にx == ''が表示され、空白になることがあります。 https://docs.python.org/3.6/library/stdtypes.html?highlight=isalpha#str.isalpha

'' .joinはフィルタの結果を受け取り、あなたのために文字列に戻します。 https://docs.python.org/3.6/library/stdtypes.html?highlight=isalpha#str.join

0

それとも、あなたが期待されるだろうと、それはまた「氏」として句読点の一般的な落とし穴を避けるよう、文のトークン化を行い、あなたのテキストをトークン化するためにnltkパッケージを使用することができます - >これは句読点に基づいて分類されません。

from nltk.tokenize import word_tokenize 
string = "Hello there, friend" 
words = word_tokenize(string) 
print(words) 

OUTPUT

['Hello', 'there', ',', 'friend'] 

だから私は、あなたがnltkパッケージを使用して試してみて、それが動作するかどうかを確認する必要がありますね。

このリンクをクリックしてください。here

希望します。

関連する問題