如何在python中将多行转换为多个列表?

2024-03-28 17:44:37 发布

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


Tags: python
2条回答

你所有的数据格式都一样吗?如果是,请使用re库中的regex。你知道吗

import re
your_str="[36.147315849999998, -86.7978174] 6 2011-08-28 19:45:11 @maryreynolds85 That is my life, lol."
reg_data= re.compile(r"\[(.*),(.*)\] (.*)")
your_reg_grp=re.match(reg_data,your_str)
if your_reg_grp:
  print(your_reg_grp.groups())

#这应该把除了方括号外的部分以外的所有内容都放在列表中,您可以通过拆分(“”)来拆分最后一个部分,然后创建一个新列表。你知道吗

grp1=your_reg_grp.groups()
grp2=grp1[-1].split(" ")

组合grp1[:-1]和grp2

您已经在创建列表中需要的单词。你只需创建一个列表并将其添加到列表中。你知道吗

with open('aabb.txt') as t:
        for Line in t:
            list=[]
            splitline = Line.strip()  
            splitline2 = splitline.split()  
            for words in splitline2:
                words = words.strip("!#$%&'()*+,-./:;?@[\]^_`{|}~")
                words = words.lower()
                list.append(words)
            print(list)

您还可以为每一行创建一个列表,并根据您的需要使用它。你知道吗

with open('aabb.txt') as t:
        root_list=[]
        for Line in t:
            temp_list=[]
            splitline = Line.strip()  
            splitline2 = splitline.split()  
            for words in splitline2:
                words = words.strip("!#$%&'()*+,-./:;?@[\]^_`{|}~")
                words = words.lower()
                temp_list.append(words)
            root_list.append(temp_list)
        print(root_list)

相关问题 更多 >