1

定義したセットをリストに変換して、インデックス作成に使用できるようにしようとしています。

seen = set()
for line in p:
   for word in line.split():
       if word not in seen and not word.isdigit():
           seen.add(word)          
been = list(seen)

セットには問題なくアイテムが含まれているようです。ただし、変数エクスプローラーでその値を監視するとき (および後でインデックス関数を呼び出すとき)、リストは常に空です。

私は何を間違っていますか?

編集:これはコード全体です。「o」の「p」の単語の位置を見つけ、その出現回数を 1 行でグラフ化しようとしています。それは単語の巨大なリストなので、手動で何かを入力することは問題外です.

p = open("p.txt", 'r')
o = open("o.txt", 'r')
t = open("t.txt", 'w')
lines = p.readlines()
vlines = o.readlines()
seen = set()
for line in p:
   for word in line.split():
       if word not in seen and not word.isdigit():
           seen.add(word)          
been = list(seen)
for i in lines:
        thisline = i.split();
        thisline[:] = [word for word in thisline if not word.isdigit()]
        count = len(thisline)
        j = []
        j.append(count)
        for sword in thisline:
             num = thisline.count(sword)
             #index=0
             #for m in vlines:
                 #if word is not m:
                 #index+=1
            ix = been.index(sword)
            j.append(' ' + str(ix) + ':' + str(num))
        j.append('\n')
for item in j:
  t.write("%s" % item)

出力は、「(行内のアイテムの総数) (インデックス):(出現回数)」の形式である必要があります。私はかなり近いと思いますが、この部分は私を悩ませています。

4

2 に答える 2

2

あなたのコードは問題なく動作しています。

>>> p = '''
the 123 dogs
chased 567 cats
through 89 streets'''.splitlines()
>>> seen = set()
>>> for line in p:
       for word in line.split():
           if word not in seen and not word.isdigit():
               seen.add(word)


>>> been = list(seen)
>>> 
>>> seen
set(['streets', 'chased', 'cats', 'through', 'the', 'dogs'])
>>> been
['streets', 'chased', 'cats', 'through', 'the', 'dogs']
于 2013-11-05T04:57:09.980 に答える
0

行ごとに読みたい理由がない限り、これを単に置き換えることができます:

seen = set()
for line in p:
   for word in line.split():
       if word not in seen and not word.isdigit():
           seen.add(word)          
been = list(seen)

と:

been = list(set([w for w in open('p.txt', 'r').read().split() if not w.isdigit()]))
于 2013-11-05T06:42:27.783 に答える