【问题标题】:how do I create dictionary keys from a list [closed]如何从列表中创建字典键 [关闭]
【发布时间】:2015-03-07 22:13:27
【问题描述】:

我一直在尝试创建一个脚本,用于在文本文件中搜索模式,计算它出现的次数,然后将其作为键值对插入字典中。

代码如下:

fname = raw_input("File name: ")
import re
vars = dict()
lst= list()
count = 0

try:
    fhand = open(fname, "r+")
except:
    print "File not found"
quit()  

for line in fhand:
    line.rstrip()
    if re.search(pattern , line):
        x = re.findall(pattern , line)
        lst.append(x)
    else:
        continue
    for x in lst:
        count += 1

从正则表达式方法中提取文本并将其插入字典使其看起来像这样的最佳方法是什么:

{'pattern' : count, 'pattern' : count, 'pattern' : count}

【问题讨论】:

  • 您是否有多个唯一模式要作为键存储在字典中?
  • 我要存储的文本字符串格式相同,但长度和字符不同
  • 我认为您必须向我们提供一些具体的示例输入文本以及您要计算的模式类型。您不能在字典中多次使用相同的键,但我怀疑您的意思是说示例中的不同“模式”实际上是不同的。

标签: python regex string list dictionary


【解决方案1】:

你可以这样做:

fhand = ["<abc> <abc>", "<abc>", "<d>"]

counts = {}
pattern = re.compile(r'<\w+>') # insert your own regex here

for line in fhand:
    for match in pattern.findall(line):
        # initialize the count for this match to 0 if it does not yet exist
        counts.setdefault(match, 0)
        counts[match] += 1

给予

counts = {'<abc>': 3, '<d>': 1}

【讨论】:

  • 谢谢!这非常有效!
【解决方案2】:

你的意思是这样的吗?

import re

pattern1 = r'([a-z]+)'
pattern2 = r'([0-9])'

regex1 = re.compile(pattern1)
regex2 = re.compile(pattern2)

filename = "somefile.txt"

d = dict()

with open(filename, "r") as f:
    for line in f:
        d[pattern1] = d.get(pattern1, 0) + len(regex1.findall(line));
        d[pattern2] = d.get(pattern2, 0) + len(regex2.findall(line));

print d
# output: {'([0-9])': 9, '([a-z]+)': 23}

【讨论】:

    【解决方案3】:

    首先,我会使用with 而不仅仅是open 打开您的文件。

    例如:

    with open(fname, "r+") as fhand:
    

    另外,我认为您误解了字典的意义。它们是键/值存储,这意味着每个键都是唯一的。您不能拥有多个密钥。

    我认为更好的解决方案如下:

    import collections 
    
    for line in fhand:
    line.rstrip()
    if re.search(pattern , line):
        x = re.findall(pattern , line)
        lst.append(x)
    else:
        continue
    
    counted = collections.Counter(lst)
    print counted
    

    这将返回一个字典,其中包含您的列表中出现的键/值,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-08
      • 2020-07-29
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 2017-07-27
      • 2014-02-10
      • 1970-01-01
      相关资源
      最近更新 更多