加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python解析并从行获取更多输入

发布时间:2020-12-20 12:06:48 所属栏目:Python 来源:网络整理
导读:我需要解析一个文本文件并获取输出并将它们添加到列表中. with open(qwer.txt,'r') as my_file: a = my_file.readlines() for line in a: for part in line.split(): if "color=" in part: p1 = part.split('=')[1] print(p1) list1 = [] p1.append(list1)
我需要解析一个文本文件并获取输出并将它们添加到列表中.

with open(qwer.txt,'r') as my_file:
        a = my_file.readlines()
        for line in a:
            for part in line.split():
                if "color=" in part:
                    p1 = part.split('=')[1] 
                    print(p1)
                    list1 = []  
                    p1.append(list1)

所以,我有一条线,我在同一条线上有两个/更多“color =”,我需要输出来获得两种颜色:

my color=red and my color=green

我想要的输出是:

red
green

我需要将它们分别添加到列表中作为[‘red’,’green’].请帮忙!答案将不胜感激.

解决方法

你当然可以使用正则表达式:

import re
str = "my color=red and my color=green"
p = r'color=([a-z]+)'
x = re.findall(p,str)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读