2

鉴于 infile 包含:

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

如何获取outfile为:

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')                

我的代码有什么问题,请帮忙!问题在这里已经解决了: 用python写的代码有什么问题

4

3 回答 3

3

通常你可以在没有正则表达式的情况下解决字符串操作问题,因为 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
于 2013-09-07T15:25:54.560 回答
3

正则表达式会更容易:

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')
于 2013-09-07T15:28:31.117 回答
1

您可以使用正则表达式,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'
于 2013-09-07T15:17:30.657 回答