このスクリプトの目標は、テキストファイルでフォルダ全体を取り込み、すべてのファイルの各行を取り込み、すべての一意の行を含むファイルを降順周波数のオーダー。1ギガバイト分のテキストを1つのファイルにまとめて、出現数でソートします。
これは、一意の行を見つけるだけでなく、すべてのファイルに各一意の行がどれくらい頻繁に出現するかを検出します。
このスクリプトでは、多くのテキストを処理する必要があります。つまり、少なくとも2GBほどであるため、効率的に処理する必要があります。 これまでのところ、私はこの目標を達成していません。
import os, sys #needed for looking into a directory
from sys import argv #allows passing of arguments from command line, where I call the script
from collections import Counter #allows the lists to be sorted by number of occurrences
#Pass argument containing Directory of files to be combined
dir_string = str((argv[1]))
filenames=[]
#Get name of files in directory, add them to a list
for file in os.listdir(dir_string):
if file.endswith(".txt"):
filenames.append(os.path.join(dir_string, file)) #add names of files to a list
#Declare name of file to be written
out_file_name = dir_string+".txt"
#Create output file
outfile = open(out_file_name, "w")
#Declare list to be filled with lines seen
lines_seen = []
#Parse All Lines in all files
for fname in filenames: #for all files in list
with open(fname) as infile: #open a given file
for line in infile: #for all lines in current file, read one by one
#Here's the problem.
lines_seen.append(str(line).strip('\n')) #add line to list of lines seen,
#removing the endline
#Organizes the list by number of occurences, but produced a list that contains
# [(item a, # of a occurrences), (item b, # of b occurrences)...]
lines_seen = Counter(lines_seen).most_common()
#Write file line by line to the output file
for item in lines_seen: outfile.write(str(item[0])+"\n")
outfile.close()
エラーメッセージが表示されたら、それは約lines_seen.append(str(line).strip('\n'))
です。
私はまず文字列とストリッピングに変換せずに行を追加しようとしましたが、私に受け入れられない文字列には '\ n'が含まれていました。 小規模なリストの場合、文字列とストリッピングに変換することはあまりにもメモリ課税ではありませんでした。 Linuxではまだ試していません - 私は私のPC上で終了行の文字
を取り除くのより効率的な方法を見つけ出すことができませんでした 、これはこれは私にKilled: 9
を与える私のMac上で、MemoryError
の原因となります。
バイナリに変換し、順序リストをアセンブルしてから変換する必要がありますか? これ以外にどのようにすることができますか?
EDIT - それは私がこれを行うための最善の全体的な方法は明らかになってきたが、UNIXとあった
cd DirectoryWithFiles
cat *.txt | sort | uniq -c | sort -n -r > wordlist_with_count.txt
cut -c6- wordlist_with_count.txt > wordlist_sorted.txt
'List'をメモリに保存するのではなく、なぜあなたの行を一時ファイルに書き込まないのですか? –
これを書いている時点で、リストに入れないでファイルを並べ替える方法がわからず、同じ問題に戻ってくるのですか? – berzerk0
このスレッドに従ってください:http://stackoverflow.com/questions/41315394/ file-size-limit-for-readあなたは2GBまでのファイルを読むことができます –