python编写的代码有什么问题 [英] what is wrong in the code written inpython

查看:70
本文介绍了python编写的代码有什么问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于infile包含:

Given that the infile contains:

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

如何通过以下方式获取外发文件:

How to obtain the outfile as:

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

但是代码产生空白文件.怎么了?

But the code produces blank file. What is wrong with it??

推荐答案

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

Your code have only one major problem: if item_set2.endswith ('KB') check doesn't work since there is a new-line char at the end of each line. Replace it with (note strip() call):

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

此外,您不需要+ '\n',因为item_set2已在末尾包含换行符:

Also, you don't need + '\n' since item_set2 already contains a new-line at the end:

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

仅供参考,您可以将正则表达式与保存组一起使用以提取数据:

FYI, you can use regex with saving groups to extract the data:

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

这篇关于python编写的代码有什么问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆