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' 中找到单词的位置,并在一行中绘制它的出现次数。这是一个巨大的单词列表,因此手动输入任何内容都是不可能的。

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 回答