输入的代码有什么问题

2024-09-25 00:30:48 发布

您现在位置: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')  

但是代码生成了一个空白文件。怎么了??你知道吗


Tags: 文件intxtforlineopenitemoutfile
3条回答

无需导入re的解决方案。该条件可以改进为单线条件。你知道吗

with open('test.txt', 'r') as infile, open('outfile.txt', 'w') as outfile:
    for line in infile:
        filename = line.strip().split('"')[1]
        size = line.rsplit(None, 1)[-1]
        if filename.endswith('.jpg') and size.endswith('KB'):
            outfile.write('%s %s\n' % (filename, size))

您的代码只有一个主要问题:if item_set2.endswith ('KB')检查不起作用,因为每行末尾都有一个新行字符。替换为(注意strip()调用):

if item_set2.strip().endswith('KB'):

另外,您不需要+ '\n',因为item_set2已经在末尾包含了新行:

outfile.write (item_set1 + ' ' + item_set2.strip())

仅供参考,您可以将regex与保存组一起使用来提取数据:

import re


with open('test.txt', 'r') as infile, open('outfile.txt', 'w') as outfile:
    for line in infile:
        match = re.search(r'"(.*)"\w+\s(\w+)', line)
        outfile.write(' '.join(match.groups()) + "\n")

运行代码后outfile.txt的内容:

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

您应该使用regex,这将简化您的代码。比如:

import re
with open ('test.txt', 'r') as infile, open ('outfile.txt', 'w') as outfile:
    for line in infile:
        obj = re.match('.+"(.+\.jpg)".+\s(\d+KB)', line)
        if obj:
             outfile.write (obj.group(1) + ' ' + obj.group(2) + '\n') 

你知道吗输出文件.txt此脚本返回:

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

相关问题 更多 >