1

標準辞書のすべての単語を変換したい (例: unix マシンの /usr/share/dict/words ) 整数と、辞書内の 2 つの単語ごとに XOR を検索し (もちろん、それらを整数に変換した後)、おそらくそれを保存します。新しいファイルで。

私はPythonが初めてで、ファイルサイズが大きいため、プログラムが時々ハングします。

import os
dictionary = open("/usr/share/dict/words","r")
'''a = os.path.getsize("/usr/share/dict/words")
c = fo.read(a)'''
words = dictionary.readlines()

foo = open("word_integer.txt", "a")


for word in words:
    foo.write(word)
    foo.write("\t")
    int_word = int(word.encode('hex'), 16)
    '''print int_word'''
    foo.write(str(int_word))
    foo.write("\n")

foo.close()
4

2 に答える 2

2

まず、文字列を int に変換するメソッドが必要です。それを作成します (あなたがしていることは私にはまったく機能しないため、Unicode としてエンコードするつもりですか?):

def word_to_int(word):
    return sum(ord(i) for i in word.strip())

次に、ファイルを処理する必要があります。以下は Python 2.7 以降で機能します (2.6 では、ブロックを使用して 2 つを別々にネストするか、次を使用しますcontextlib.nested

with open("/usr/share/dict/words","rU") as dictionary: 
    with open("word_integer.txt", "a") as foo:
        while dictionary:
            try:
                w1, w2 = next(dictionary), next(dictionary)
                foo.write(str(word_to_int(w1) ^ word_to_int(w2)))
            except StopIteration:
                print("We've run out of words!")
                break
于 2014-03-02T23:17:49.203 に答える
0

このコードは私にとってはうまくいくようです。ファイル全体を呼び出しreadlines()て一度にすべてをメモリに取り込むため、効率の問題が発生している可能性があります。

このソリューションは、ファイルを各行ごとにループし、xor を計算します。

f = open('/usr/share/dict/words', 'r')                                          

pairwise_xors = {}                                                              

def str_to_int(w):                                                              
    return int(w.encode('hex'), 16)                                             

while True:                                                                     
    line1 = f.readline().strip()                                                
    g = open('/usr/share/dict/words', 'r')                                      
    line2 = g.readline().strip()                                                

    if line1 and line2:                                                         
        pairwise_xors[(line1, line2)] = (str_to_int(line1) ^ str_to_int(line2)) 
    else:                                                                       
        g.close()                                                               
        break                                                                   

f.close()             
于 2014-03-02T22:47:51.860 に答える