4

このコードを実行すると、いくつかの grep:write エラーが発生します。私は何が欠けていますか?

これはほんの一部です:

     while d <= datetime.datetime(year, month, daysInMonth[month]):
        day = d.strftime("%Y%m%d")
        print day
        results = [day]
        first=subprocess.Popen("grep -Eliw 'Algeria|Bahrain' "+ monthDir +"/"+day+"*.txt | grep -Eliw 'Protest|protesters' "+ monthDir +"/"+day+"*.txt", shell=True, stdout=subprocess.PIPE, )
        output1=first.communicate()[0]
        d += delta
        day = d.strftime("%Y%m%d")
        second=subprocess.Popen("grep -Eliw 'Algeria|Bahrain' "+ monthDir +"/"+day+"*.txt | grep -Eliw 'Protest|protesters' "+ monthDir +"/"+day+"*.txt", shell=True,  stdout=subprocess.PIPE, )
        output2=second.communicate()[0]
        articleList = (output1.split('\n'))
        articleList2 = (output2.split('\n'))
        results.append( len(articleList)+len(articleList2))
        w.writerow(tuple(results))
        d += delta
4

3 に答える 3

8

あなたがするとき

A | B

シェルでは、プロセス A の出力がプロセス B に入力としてパイプされます。プロセス B がプロセス A のすべての出力を読み取る前にシャットダウンした場合 (たとえば、-lオプションの機能である、探していたものを見つけたため)、プロセス A は、その出力パイプが時期尚早に閉じられたことを訴える場合があります。

stderrこれらのエラーは基本的に無害であり、サブプロセスを にリダイレクトすることで回避できます/dev/null

ただし、より良いアプローチは、単純に Python の強力な正規表現機能を使用してファイルを読み取ることです。

def fileContains(fn, pat):
    with open(file) as f:
        for line in f:
            if re.search(pat, line):
                return True
    return False

first = []
for file in glob.glob(monthDir +"/"+day+"*.txt"):
    if fileContains(file, 'Algeria|Bahrain') and fileContains(file, 'Protest|protesters'):
        file.append(first)
于 2013-03-31T09:31:03.197 に答える
1

単語全体を探しているだけの場合は、count()メンバー関数を使用できます。

# assuming names is a list of filenames
for fn in names:
    with open(fn) as infile:
        text = infile.read().lower()
    # remove puntuation
    text = text.replace(',', '')
    text = text.replace('.', '')
    words = text.split()
    print "Algeria:", words.count('algeria')
    print "Bahrain:", words.count('bahrain')
    print "protesters:", words.count('protesters')
    print "protest:", words.count('protest')

より強力なフィルタリングが必要な場合は、 を使用しますre

于 2013-03-31T09:22:16.847 に答える