python - 从集合转换时列表为空

标签 python

我正在尝试将我定义的集合转换为列表,以便我可以将其用于索引。

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)

输出应采用以下格式:“(行中的项目总数)(索引):(出现次数)”。 我认为我已经很接近了,但这部分困扰着我。

最佳答案

您的代码运行良好。

>>> 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']

关于python - 从集合转换时列表为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19782119/

相关文章:

python - 如何有效地从大小为 n 的列表中获取大小为 {n, n-1,n-2, ... 1} 的所有排列?

python - Django无法导入任何包: AttributeError: __name__

python - 自定义 Python 库仅在 ArchLinux 中引发 ImportError

python - 使用python逼近导数

python - 离线安装Django

python - SQLite/SQLAlchemy : how to enforce Foreign Keys?

python - 使用 SQLAlchemy Integer 字段创建用于过滤的 timedelta 对象

python - django 中的 get_user_model() 、settings.AUTH_USER_MODEL 和 USER 有什么区别?

python - 从字符串中提取换行符

python - 拆分数据框中的每个单元格( Pandas / python )