我有一个包含行的文件,如下所示:
"[36.147315849999998, -86.7978174] 6 2011-08-28 19:45:11 @maryreynolds85 That is my life, lol."
"[37.715399429999998, -89.21166221] 6 2011-08-28 19:45:41 Ate more veggie and fruit than meat for the first time in my life"我尝试剥离这些行并将它们拆分,然后尝试剥离每个带有标点符号的列表中的子字符串。
with open('aabb.txt') as t:
for Line in t:
splitline = Line.strip()
splitline2 = splitline.split()
for words in splitline2:
words = words.strip("!#$%&'()*+,-./:;?@[\]^_`{|}~")
words = words.lower()我应该怎么做才能将这些行转换为两个列表,如下所示:
'["36.147315849999998","-86.7978174","6","2011-08-28","19:45:11","maryreynolds85","that","is","my","life","lol"]'
'["37.715399429999998","-89.21166221","6","2011-08-28","19:45:41","ate","more","veggie","and","fruit","than","meat","for","the","time","in","my","life"]'发布于 2019-11-05 13:11:05
您的所有数据是否都采用相同的格式?如果是,使用re库中的正则表达式。
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())#这应该把所有的东西都放在列表中,除了方括号之外的部分,你可以用split(“")拆分最后一个部分,然后创建一个新的列表。
grp1=your_reg_grp.groups()
grp2=grp1[-1].split(" ")组合grp1:-1和grp2
发布于 2019-11-05 13:49:44
您已经在创建列表中需要的单词。您只需创建一个列表并将其添加到列表中。
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)https://stackoverflow.com/questions/58704797
复制相似问题