【问题标题】:Type error: unhashable type: 'list' (using sets) [duplicate]类型错误:不可散列类型:'list'(使用集合)[重复]
【发布时间】:2018-04-11 01:48:18
【问题描述】:

我只想将两个文本中的单词放在一个集合中,以获取所有唯一的单词。当我运行此代码时,我得到一个 Type Error: unhashable type: 'list'

我可以做些什么不同的事情?

infile1 = open("random.txt", 'r')
infile2 = open("random_encr.txt", 'r')

data1 = infile1.read()
data2 = infile2.read()

#close files
infile1.close()
infile2.close()

# replace all dots with empty string
data1 = data1.replace('.', '')
data2 = data2.replace('.', '')

# split words in data (splitted by whitespace) and save in words
words1 = data1.split()
words2 = data2.split()

set1 = set([words1])
set2 = set([words2])

set1.update(set2)

print(set1)

【问题讨论】:

  • 您在哪一行出现此错误?
  • 啊,您似乎正在使用列表列表初始化集合。 words1 是一个列表,[words1] 类似于 [['word1', 'word2', ...]]。你可以试试set1 = set(words1) 吗?
  • 是的,你可能是对的。错误在第 19 行,我在这里创建集合
  • 您可以做的不同的事情是创建一个函数,该函数返回给定文件名的单词集。你的代码几乎有一半是重复的。
  • 如果您正在处理繁重的文本工作,我建议您使用 NLTK。是一个用于文本处理的 python 包,具有​​“标记化”文本等功能。

标签: python


【解决方案1】:

问题是您传递给set 的参数中有错误:

set1 = set([words1]) 正在定义一个项目列表 - 包含单词列表。

  • 例如:[["a", "b", "c"]] ...
  • 我猜你只想要["a", "b", "c"]

删除[] 并执行set1 = set(words1)

【讨论】:

  • 是的,正如 kedder 在 cmets 中也提到的,这是我的问题。非常感谢!
【解决方案2】:

以下是生成任一文档中出现的所有单词列表的一种方法:

infile1 = open("1.txt", 'r')
infile2 = open("2.txt", 'r')

data1 = infile1.read()
data2 = infile2.read()

#close files
infile1.close()
infile2.close()

# replace all dots with empty string
data1 = data1.replace('.', '')
data2 = data2.replace('.', '')

# split words in data (splitted by whitespace) and save in words
words1 = data1.split()
words2 = data2.split()

#create combined list
combinedList = []

for word in words1:
    if word not in combinedList:
        combinedList.append(word)

for word in words2:
    if word not in combinedList:
        combinedList.append(word)

print(combinedList)

【讨论】:

  • 对不起,这条评论在这里不合适,但我不知道如何删除它。如果您正在处理繁重的文本工作,我建议您使用 NLTK。是一个用于文本处理的 python 包,具有​​“标记化”文本等功能。
  • 毫无疑问(我一直使用 nltk)!我只是想向用户展示如何稍微修改他们的代码以获得他们想要的功能。
  • 是的,我看错了,我的评论是给拉格纳的,不是给你的。 :D
猜你喜欢
  • 1970-01-01
  • 2017-12-27
  • 2018-08-03
  • 1970-01-01
  • 2018-04-23
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多