如何组合文件列表中的项目?

时间:2017-06-16 00:10:48

标签: python list file

我在文本文件中有一个列表如下:

-[foo1
-[foo2
-[bar1
-[bar2
*etc*

如何将这些项目组合起来只打印'foo'和'bar'?

我尝试过像

这样的东西
 data=open("file", 'r').readlines()
for n, line in enumerate(data):
if line.startswith("foo"):
    print "foo"
if line.startswith("bar"):
    print "bar"

当有很多这些项目需要合并时,是否有更好的解决方案?

2 个答案:

答案 0 :(得分:1)

您正在寻找每行的第一个单词,并且只想打印一个给定的单词吗?

import re

def first_word(line):
    match = re.search("[A-Za-z]+")
    if match:
        return match.group(0)
    else:
        return None

with open("file.txt") as data:
    seen = {None}
    for line in data:
        word = first_word(line)
        if word not in seen:
            print(word)
            seen.add(word)

如果您不关心打印单词的顺序,可以简化为

with open("file.txt") as data:
    words = set(first_word(line) for line in data)

words.discard(None)
print("\n".join(words))

答案 1 :(得分:1)

假设输入文件如下所示:

foo1
foo2
foo3
bar1
bar2
bar3
car1
car2
car3

你可以从单词的末尾删除数字,计算文件中有多少单词,然后打印单词出现的次数。

代码看起来像这样:

data = open("list.txt").readlines()
items = []
item_count = []
for line in data:
    x = ''.join([i for i in line if not i.isdigit()]).replace("\n","")
    if x in items:
        y = items.index(x)
        item_count[y] += 1
    else:
        items.append(x)
        item_count.append(1)
for x in range(len(items)):
    print (items[x] + " * " + str(item_count[x]))

这将产生如下输出:

foo * 3
bar * 3
car * 3

这是你在找什么?

相关问题