2016-11-28 2 views
1

私はテロ攻撃に関するさまざまなニュース記事を含むテキストを持っています。各記事はhtmlタグ(<p>Advertisement)で始まり、各記事から特定の情報、すなわちテロ攻撃で負傷した人の数を抽出したいと思います。正規表現とcsv |より読みやすい出力

これは、テキストファイルのサンプルとどのように記事が分離されている。

[<p>Advertisement , By MILAN SCHREUER and  ALISSA J. RUBIN OCT. 5, 2016 
, BRUSSELS — A man wounded 2 police officers with a knife in Brussels around noon on Wednesday in what the authorities called “a potential terrorist attack.” , The two officers were attacked on the Boulevard Lambermont.....] 
[<p>Advertisement ,, By KAREEM FAHIM and MOHAMAD FAHIM ABED JUNE 30, 2016 
, At least 33 people were killed and 25 were injured when the Taliban bombed buses carrying police cadets on the outskirts of Kabul, Afghanistan, on Thursday. , KABUL, Afghanistan — Taliban insurgents bombed a convoy of buses carrying police cadets on the outskirts of Kabul, the Afghan capital, on Thursday, killing at least 33 people, including four civilians, according to government officials and the United Nations. , During a year...] 

これは、これまでの私のコードです:

text_open = open("News_cleaned_definitive.csv") 
text_read = text_open.read() 
splitted = text.read.split("<p>") 
pattern= ("wounded (\d+)|(\d+) were wounded|(\d+) were injured") 
for article in splitted: 
    result = re.findall(pattern,article) 

私が手出力は次のようになります。

[] 
[] 
[] 
[('', '40', '')] 
[('', '150', '')] 
[('94', '', '')] 

出力をより読みやすくして、それをcsvファイルとして保存したいと考えています:

article_1,0 
article_2,0 
article_3,40 
article_3,150 
article_3,94 

どのように読みやすくするための提案ですか?

答えて

1

あなたがそれを要求したので、私はこのようなあなたのループを書き直しとcsv書き込みと合併:場合の犠牲者の数(以上1未満enumerate

  • 合計を使用して、物品の

    import csv 
    
    with open ("wounded.csv","w",newline="") as f: 
        writer = csv.writer(f, delimiter=",") 
        for i,article in enumerate(splitted): 
         result = re.findall(pattern,article) 
         nb_casualties = sum(int(x) for x in result[0] if x) if result else 0 
         row=["article_{}".format(i+1),nb_casualties] 
         writer.writerow(row) 
    
    • GETインデックスをグループマッチ)を使って整数に変換し、何かが一致した場合にのみsumに渡します(三項式でチェックします)
    • を印刷するか、オプションで、csv.writerオブジェクトの行(1回の繰り返しにつき1行)として書き込みます。
  • +0

    私が探していたものです。私はそれをいかに適切に保存できるのだろうと思っていましたか? f: ライター= csv.writer(f、区切り文字= "、") writer.writerows([行]) ' –

    +0

    あなたが持っている(" wounded.csv "、" w "、改行=" "それはほぼ正しい!それは私の答えであなたのためにそれを編集してみましょうので、それはきれいです。 –

    +0

    [OK]を1ヶ月後、私はあなたが私のお気に入りの管理者だと言うことができます。 –