質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

2回答

1015閲覧

文章のワードカウントをリストアップしたい

kay_ventris4

総合スコア269

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2020/10/09 16:11

編集2020/10/11 00:38

###やってみたいこと
記事(英語)から適当に引っ張ってきた文章に使われる単語をその出現回数とともにリストアップしたい。
(※記事の内容は適当に見つけたものを繋げたりしています)

###該当コード

python

1 2words=[] 3str=" The agency was given the prize for its efforts to combat hunger and improve conditions for peace. The WFP, the 101st winner of a prize now worth 10m Swedish krona ($1.1m; £875,000), said it was 'deeply humbled' to have won. Some 107 organisations and 211 individuals were nominated for the award this year. WFP head David Beasley told the BBC's Newshour he was in shock following the announcement. In the video, Mr Prasad says he and his wife start preparing the menu at 6.30am every morning and finish by 9.30am. The first lot of customers are usually informal workers or office-goers looking for a hearty breakfast. But the pandemic, which cost people their jobs or forced them to stay at home, has shrunk business. Mrs Prasad says that at times they take the unsold food back home, and on some days, they don't have money to cook a meal for themselves. But ever since the video went viral, the stall has seen a steady flow of customers, some of whom are eager to squeeze in a selfie with the now-famous spot. TV crews have been showing up as the stall and its owners continue to grab headlines. Bollywood actress Sonam Kapoor and cricketer R Ashwin are among those who have offered to help. Mr Wasan told ANI that he had come across Baba ka dhaba by chance. 'They told me that were making losses every day. So I made a video at the spot and shared it with my followers.' He adds that he has collected around $2,700 in donations to repair the stall and the couples house. The Prasads are both touched and elated. 'It is all because of Gaurav that the customers have lined up today,' Mr Prasad told ANI news agency. 'Yesterday there was almost no sales. Today I feel that the whole country is with us.' " 4for i in str.split(): 5 if type(i)!=int: 6 words.append(i.lower()) 7 for j in words: 8 print(j+': '+words.count(j)+'\n')

###エラー
Terminal上で以上のプログラムを実行すると、以下のエラーが出力されます:

python

1 File "/Users/***/Desktop/math.py", line 9, in <module> 2 print(j+': '+words.count(j)+'\n') 3TypeError: can only concatenate str (not "int") to str

###やってみたこと
様々な工夫をしてintの文字列が含まれない様にしたのですが、何故かその処理をする前した後同じ上のエラーが出力されます。お力添え頂ける箇所がございましたら、よろしくお願い申し上げます。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

ベストアンサー

  • 結果の表示は、最初のforループの中ではなく、繰り返し処理がすべて終わってからにする。つまり、2つめのforループは最初のforループの外側に置く。
  • エラーの原因は、words.count(j)が整数値を返すことにあるので、組み込み関数のstrで囲んで文字列に変換する
  • そのさい、英文を格納する変数名がstrのままだと、同じ名前の組み込み関数strが使えなくなってしまう。以下のコードでは、英文をsampleという別の名前の変数に格納している。
  • printは、ほっといても末尾で改行するのが既定値なので、\nは不要。

Python

1words = [] 2sample = " The agency was given the prize for its efforts to combat hunger and improve conditions for peace. The WFP, the 101st winner of a prize now worth 10m Swedish krona ($1.1m; £875,000), said it was 'deeply humbled' to have won. Some 107 organisations and 211 individuals were nominated for the award this year. WFP head David Beasley told the BBC's Newshour he was in shock following the announcement. In the video, Mr Prasad says he and his wife start preparing the menu at 6.30am every morning and finish by 9.30am. The first lot of customers are usually informal workers or office-goers looking for a hearty breakfast. But the pandemic, which cost people their jobs or forced them to stay at home, has shrunk business. Mrs Prasad says that at times they take the unsold food back home, and on some days, they don't have money to cook a meal for themselves. But ever since the video went viral, the stall has seen a steady flow of customers, some of whom are eager to squeeze in a selfie with the now-famous spot. TV crews have been showing up as the stall and its owners continue to grab headlines. Bollywood actress Sonam Kapoor and cricketer R Ashwin are among those who have offered to help. Mr Wasan told ANI that he had come across Baba ka dhaba by chance. 'They told me that were making losses every day. So I made a video at the spot and shared it with my followers.' He adds that he has collected around $2,700 in donations to repair the stall and the couples house. The Prasads are both touched and elated. 'It is all because of Gaurav that the customers have lined up today,' Mr Prasad told ANI news agency. 'Yesterday there was almost no sales. Today I feel that the whole country is with us.' " 3 4for i in sample.split(): 5 words.append(i.lower()) 6 7for j in words: 8 print(j + ': ' + str(words.count(j)))

追加分: 標準ライブラリのcollectionに含まれるCounterクラスを使うと、リストの各要素を数えてソートした辞書を作ってくれる。

Python

1import collections 2 3words = [] 4sample = " The agency was given the prize for its efforts to combat hunger and improve conditions for peace. The WFP, the 101st winner of a prize now worth 10m Swedish krona ($1.1m; £875,000), said it was 'deeply humbled' to have won. Some 107 organisations and 211 individuals were nominated for the award this year. WFP head David Beasley told the BBC's Newshour he was in shock following the announcement. In the video, Mr Prasad says he and his wife start preparing the menu at 6.30am every morning and finish by 9.30am. The first lot of customers are usually informal workers or office-goers looking for a hearty breakfast. But the pandemic, which cost people their jobs or forced them to stay at home, has shrunk business. Mrs Prasad says that at times they take the unsold food back home, and on some days, they don't have money to cook a meal for themselves. But ever since the video went viral, the stall has seen a steady flow of customers, some of whom are eager to squeeze in a selfie with the now-famous spot. TV crews have been showing up as the stall and its owners continue to grab headlines. Bollywood actress Sonam Kapoor and cricketer R Ashwin are among those who have offered to help. Mr Wasan told ANI that he had come across Baba ka dhaba by chance. 'They told me that were making losses every day. So I made a video at the spot and shared it with my followers.' He adds that he has collected around $2,700 in donations to repair the stall and the couples house. The Prasads are both touched and elated. 'It is all because of Gaurav that the customers have lined up today,' Mr Prasad told ANI news agency. 'Yesterday there was almost no sales. Today I feel that the whole country is with us.' " 5for i in sample.split(): 6 words.append(i.lower()) 7 8counter = collections.Counter(words) 9for key in counter: 10 print(key + ': ' + str(counter[key]))

投稿2020/10/09 16:25

編集2020/10/10 01:20
Daregada

総合スコア11990

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

kay_ventris4

2020/10/09 16:56

出来ました! 細かいところの指導までありがとうございます。一気に知識が増えました。
LouiS0616

2020/10/10 00:58

あと if type(i) != int: は不要かなと思いました。 なんでこれが入っているのでしょう?
Daregada

2020/10/10 01:03

確かに、文字列をsplitして得られる要素はすべて文字列ですね。
kay_ventris4

2020/10/10 06:09

自分の中で数字抜きの単語だけのリストアップを目標にしていたので、int型の文字列を排除しました。説明が不足していました。申し訳ございません。
Daregada

2020/10/10 06:46

いや、あの書き方では「数字だけの文字列」は取り除けないんですよ。
kay_ventris4

2020/10/10 09:04

失礼ながら、どういうことでしょう。
Daregada

2020/10/10 09:14

すべて数字で構成されている文字列のデータ('170'とか)のtypeは「str」クラスです。「int」ではありません。長い文字列からsplitで得られるのは、すべて文字列のデータです。 つまり、あのforループ中のif文は「常に成立する」ので、わざわざ書く意味がありません。 「すべて数字で書かれた文字列」を対象から外したいのであれば、別の方法が必要です。
kay_ventris4

2020/10/11 02:52

なるほど、そのあたりはでは正規表現等を使って数字だけ抽出するということですね。
guest

0

エラーの原因はprint文の中で文字列と整数を「+」で結合しているからです。
数値の場合は「,」で区切ってください。
おそらく、words.count(j)がint型なので、エラーになっています。

また、print文はデフォルトでは最後に改行が入るので、'\n'は不要です。

イメージ説明

投稿2020/10/09 16:24

編集2020/10/09 16:29
takutakuya

総合スコア979

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

kay_ventris4

2020/10/09 16:57

さらに細かい回答を頂いたので他の方をベストアンサーにさせて頂きましたが、+と,の違いについては理解が曖昧だったのでよくわかりました。ありがとうございました。
takutakuya

2020/10/09 17:00

カンマで区切ると間に空白が入るので、整数を文字列にして+で結合するほうが良いかもしれませんね。 引き続き、がんばってください!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問