在python中输出具有多个条件的文件?

2024-09-25 00:25:04 发布

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

鉴于填充物包含:

aaaaaaa"pic01.jpg"bbbwrtwbbbsize 110KB
aawerwefrewqa"pic02.jpg"bbbertebbbsize 100KB
atyrtyruraa"pic03.jpg"bbbwtrwtbbbsize 190KB

如何获得输出文件:

pic01.jpg 110KB
pic02.jpg 100KB
pic03.jpg 190KB

我的代码是:

with open ('test.txt', 'r') as infile, open ('outfile.txt', 'w') as outfile:
    for line in infile:
        lines_set1 = line.split ('"')
        lines_set2 = line.split (' ')
        for item_set1 in lines_set1:
            for item_set2 in lines_set2:
                if item_set1.endswith ('.jpg'):
                    if item_set2.endswith ('KB'):
                            outfile.write (item_set1 + ' ' + item_set2 + '\n')                

我的代码有什么问题,请帮忙! 问题已经解决了: what is wrong in the code written inpython


Tags: 代码intxtforlineopenitemoutfile
3条回答

您可以使用regex和str.rsplit在这里,您的代码对于这个简单的任务来说似乎是一个多余的东西:

>>> import re
>>> strs = 'aaaaaaa"pic01.jpg"bbbwrtwbbbsize 110KB\n'
>>> name = re.search(r'"(.*?)"', strs).group(1)
>>> size = strs.rsplit(None, 1)[-1]
>>> name, size
('pic01.jpg', '110KB')

或者

>>> name, size = re.search(r'"(.*?)".*?(\w+)$', strs).groups()
>>> name, size
('pic01.jpg', '110KB')

现在使用字符串格式:

>>> "{} {}\n".format(name, size) #write this to file
'pic01.jpg 110KB\n'

通常,您可以不用regex解决字符串操作问题,因为Python有一个惊人的字符串库。在您的例子中,只需使用不同的分隔符(引号和空格)调用str.split两次就可以解决问题

演示

>>> st = """aaaaaaa"pic01.jpg"bbbwrtwbbbsize 110KB
aawerwefrewqa"pic02.jpg"bbbertebbbsize 100KB
atyrtyruraa"pic03.jpg"bbbwtrwtbbbsize 190KB"""
>>> def foo(st):
    #Split the string based on quotation mark
    _, fname, rest = st.split('"')
    #from the residual part split based on space
    #and select the last part
    rest = rest.split()[-1]
    #join and return fname and the residue
    return ' '.join([fname, rest])

>>> for e in st.splitlines():
    print foo(e)


pic01.jpg 110KB
pic02.jpg 100KB
pic03.jpg 190KB

正则表达式会更简单:

with open ('test.txt', 'r') as infile, open ('outfile.txt', 'w') as outfile:
    for line in infile:
        m = re.search('"([^"]+)".*? (\d+.B)', line)
        if m:
            outfile.write(m.group(1) + ' ' + m.group(2) + '\n')

相关问题 更多 >