「それぞれのwordがある文章の中で、何回登場するのか?」のタスクをやろうとしてます。
textと言う文章が与えられて、その文章のwordを小文字にし、それぞれのuniqueなwordの数を数えようとしているのですが、
下記の出力のように、wordだけでなく、「”」も取り出してしまっています。
原因と解決策をご教示いただけると幸いでございます。
下記は、私が試していることです。
python
1text = "As I was waiting, a man came out of a side room, and at a glance I was sure he must be Long John. His left leg was cut off close by the hip, and under the left shoulder he carried a crutch, which he managed with wonderful dexterity, hopping about upon it like a bird. He was very tall and strong, with a face as big as a ham—plain and pale, but intelligent and smiling. Indeed, he seemed in the most cheerful spirits, whistling as he moved about among the tables, with a merry word or a slap on the shoulder for the more favoured of his guests." 2 3def count_words(text): 4 """Count how many times each unique word occurs in text.""" 5 counts = dict() # dictionary of { <word>: <count> } pairs to return 6 # TODO: Convert to lowercase 7 text = text.lower() 8 # TODO: Split text into tokens (words), leaving out punctuation 9 # (Hint: Use regex to split on non-alphanumeric characters) 10 text = re.split(r"\W+", text) 11 # TODO: Aggregate word counts using a dictionary 12 for char in text: 13 counts[char] = text.count(char) 14 return counts 15 16print(count_words(text))
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。