文本fi中的列表

2024-06-14 15:33:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要你的帮助。在

我有一个文本文件包含一行的列表,每行代表一个项目列表。我需要提取频率为>;=2的所有项目并将它们输出到另一个项目中文件。这里一个例子。在

['COLG-CAD-406', 'CSAL-CAD-030', 'COLG-CAD-533', 'COLG-CAD-188']

['COLG-CAD-188']

['CSAL-CAD-030']

['EPHAG-JAE-004']

['COLG-CAD-188', 'CEM-SEV-004']

['COL-CAD-188', 'COLG-CAD-406']

输出应该是

^{2}$

以此类推直到文件结束

事先非常感谢你的帮助。在


Tags: 文件项目gt列表代表例子频率文本文件
3条回答

关于:

for x in f.readlines():
    words = ast.literal_eval(x)
    count = {}
    for w in words:        
        count[w] = count.get(w, 0) + 1
    for word, freq in count.iteritems():
        if freq >= 2:
            print word, freq

其中f是您的文件

这是一个完整的脚本,它使用regex实现您想要的功能:

from collections import defaultdict
import re

myarch = 'C:/code/test5.txt'   #this is your archive
mydict = defaultdict(int)

with open(myarch) as f:
    for line in f:
        codes = re.findall("\'(\S*)\'", line)
        for key in codes:
            mydict[key] +=1

out = []
for key, value in mydict.iteritems():
    if value > 1:
        text = "['%s'], %s" % (key, value)
        out.append(text)

#save to a file
with open('C:/code/fileout.txt', 'w') as fo:
    fo.write('\n'.join(out))

这可以简化为:

^{pr2}$

如果您使用的是Python2.7及更高版本,使用以下输入(称为list1.txt):

['COLG-CAD-406', 'CSAL-CAD-030', 'COLG-CAD-533', 'COLG-CAD-188']
['COLG-CAD-188']
['CSAL-CAD-030']
['EPHAG-JAE-004']
['COLG-CAD-188', 'CEM-SEV-004']
['COLG-CAD-188', 'COLG-CAD-406']

这个python程序:

^{pr2}$

你得到你想要的:

CSAL-CAD-030: 2
COLG-CAD-406: 2
COLG-CAD-188: 4

相关问题 更多 >