【问题标题】:How to use keys from a dictionary to search for strings?如何使用字典中的键来搜索字符串?
【发布时间】:2015-01-12 15:54:25
【问题描述】:

我正在编写一个编辑文本文件的程序。我打算让程序查找重复的字符串并删除 n - 1 行相似的字符串。

这是我目前的脚本:

import re

fname = raw_input("File name - ")
fhand = open(fname, "r+")
fhand.read()


counts = {}
pattern = re.compile(pattern)

# This searches the file for duplicate strings and inserts them into a dictionary with a counter 
# as the value

for line in fhand:
    for match in pattern.findall(line):
        counts.setdefault(match, 0)
        counts[match] += 1

pvar = {}

#This creates a new dictionary which contains all of the keys in the previous dictionary with  
# count > 1

for match, count in counts.items():
    if count > 1:
        pvar[match] = count

fhand.close()
count = 0

# Here I am trying to delete n - 1 instances of each string that was a key in the previous 
# dictionary

with open(fname, 'r+') as fhand:        
    for line in fhand:
        for match, count in pvar.items():
            if re.search(match, line) not in line: 
               continue
               count += 1
            else:
               fhand.write(line)
print count 
fhand.close()

我怎样才能使最后一点代码工作?是否可以使用字典中的键来识别相关行并删除 n-1 个实例? 还是我做错了?

编辑:来自文件的示例,这应该是一个列表,其中每个“XYZ”实例位于换行符上,前面有两个空白字符。格式有点乱,见谅 输入

-=XYZ[0:2] &
-=XYZ[0:2] &
-=XYZ[3:5] &
=XYZ[6:8] &
=XYZ[9:11] &
=XYZ[12:14] & 
-=XYZ[15:17] &
=XYZ[18:20] &
=XYZ[21:23] &

输出

=XYZ[0:2]

编辑

另外,谁能解释一下为什么代码的最后一部分没有返回任何东西?

【问题讨论】:

  • 你是什么意思 XYZ 实例?对不起,我真的不明白。我什至不“理解”输入文件。
  • 我只想删除其中包含“XYZ”的行
  • 但都包含 'XYZ' :o
  • 好吧,我理解你的意思吗:如果你有一个输入:XZY newline X3 newline XYZ1 newline P --> 期望的输出:XYZ(第一个匹配仍然存在)newline X3 newline P 是吗?
  • 是的,基本上就是这样

标签: python text dictionary editing


【解决方案1】:

这是不使用正则表达式,使用字典的东西(所以行是无序的,可能没关系......):

#!/usr/bin/env python

import os
res = {}
with open("input.txt") as f:
    for line in f.readlines():
        line = line.strip()
        key = line.split('[')[0].replace('-','').replace('=', '')
        if key in res:
            continue
        res[key] = line
        # res[key] = line.replace('&', '').strip()
print os.linesep.join(res.values())

这并没有去掉尾随的&符号。如果您想摆脱它,请取消注释:

res[key] = line.replace('&', '').strip()

【讨论】:

  • 可以用正则表达式来写吗?我需要按顺序写行
  • @VladimirEmelianov 您可以使用OrderedDict,或使用像list 这样的有序结构。不过会多一些。
猜你喜欢
  • 2021-09-15
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
相关资源
最近更新 更多