【问题标题】:Python: Create set by removing duplicates in text processing?Python:通过删除文本处理中的重复项来创建集合?
【发布时间】:2016-05-22 07:56:03
【问题描述】:

假设一个包含两列的文本文件,如下所示

A "
A "
A l
A "
C r
C "
C l
D a
D "
D "
D "
D d
R "
R "
R "
R " 
S "
S "
S o
D g
D "
D "
D "
D j
A "
A "
A z

我想检索如下信息

list1= {A:l}, {C:r,l}, {D:a,d}, {S:o}
final_list= {A:l}, {C:r,l}, {D:a,d}, R{}, {S:o}

我明白了,我必须访问文本文件line.strip().split()

然后我不知道如何继续。

【问题讨论】:

  • 无法理解逻辑。为什么{D: a} 被跳过了?到目前为止你做了什么?
  • 对不起,我错过了。更新了问题。将更新我尝试过的脚本。
  • 既然您有两个想要的字典,list1final_list,也许可以同时处理这两个字典?
  • @dwanderson :是的,list1 将用于与其他一些字典进行比较。

标签: python python-3.x text set duplicates


【解决方案1】:
import collections
list1 = collections.defaultdict(set)
final_list = collections.defaultdict(set)
for line in filetext: ## assuming youve opened it, read it in
    key, value = line.strip().split()
    final_list[key].add(value)
    if value != '"':
        list1[key].add(value)

这有点不同,final_list 将空字符串作为元素;这和你说的不符,所以我们稍微修改一下:

import collections
list1 = collections.defaultdict(set)
final_list = {}
for line in filetext: ## assuming youve opened it, read it in
    key, value = line.strip().split()
    if key not in final_list:
        final_list[key] = set()
    if value != '"':
        list1[key].add(value)
final_list.update(list1)

这应该给你你想要的东西 - 像R 这样的空集存在。

【讨论】:

  • 在第二个答案中,第二个 if 循环显示缩进错误。
  • 哪一行有缩进错误?我故意将final_list.update 放在所有行之后,因为您只需要在文件末尾执行一次。如果是其他问题,请告诉我,我会修复它
  • import collections list1 = collections.defaultdict(set) final_list = {} with open('test.txt', 'r') as f: for line in f: ## assuming youve opened it, read it in key, values = line.strip().split() if key not in final_list: final_list[key] = set() if values: list1[key].add(values) final_list.update(list1) print(list1) print(final_list)
  • final_list = {'A': {'"'}, 'C': {'r'}, 'D': {'a'}, 'R': {'"'}, 'S': {'"'}},
  • 但是你的final_list实际上是一本字典:) 不要那样做。
【解决方案2】:

如果final_list 中的字典顺序不重要

from collections import defaultdict

with open('/home/bwh1te/projects/stackanswers/wordcount/data.txt') as f:
    occurencies = defaultdict(list)
    for line in f:
        key, value = line.strip().split()
        # invoke of occurencies[key] in this condition
        # cause autocreating of this key in dict
        if value not in occurencies[key] and value.isalpha(): 
            occurencies[key].append(value)

# defaultdict(<class 'list'>, {'C': ['r', 'l'], 'D': ['a', 'd'], 'S': ['o'], 'A': ['l'], 'R': []})
# Use it like a simple dictionary

# In case if it must be a list, not a dict:
final_list = [{key: value} for key, value in occurencies.items()]
# [{'C': ['r', 'l']}, {'D': ['a', 'd']}, {'S': ['o']}, {'A': ['l']}, {'R': []}]

如果final_list中的字典顺序确实很重要:

from collections import OrderedDict

with open(file_path) as f:
    occurencies = OrderedDict()
    for line in f:
        key, value = line.strip().split()
        # Create each key anyway
        if key not in occurencies:
            occurencies[key] = []        
        if value.isalpha():
            if value not in occurencies[key]:
                occurencies[key].append(value)

# OrderedDict([('A', ['l']), ('C', ['r', 'l']), ('D', ['a', 'd']), ('R', []), ('S', ['o'])])

# In case if it must be a list, not a dict
final_list = [{key: value} for key, value in occurencies.items()]
# [{'A': ['l']}, {'C': ['r', 'l']}, {'D': ['a', 'd']}, {'R': []}, {'S': ['o']}]

list1 = [{key: value} for key, value in occurencies.items() if value]
# [{'A': ['l']}, {'C': ['r', 'l']}, {'D': ['a', 'd']}, {'S': ['o']}]

或者您可以像这样实现 OrderedDict 和 defauldict 的混合:Can I do an ordered, default dict in Python? :)

【讨论】:

  • 这里的顺序很重要。我将比较for all in list1 我将比较final_list [-1]final_list [1]
  • @Rangooski 好的...它应该保留文件记录的顺序还是按字母顺序排序?
  • 按文件记录顺序排列。不按字母顺序。
  • 非常感谢您的回答。我会尝试学习 Ordered Dict 的这个概念。
  • final_list dint 给出了预期的结果。它给了final_list = [{'A': ['l']}, {'C': ['r', 'l']}, {'D': ['a', 'd']}, {'S': ['o']}]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 2017-10-25
相关资源
最近更新 更多