我有一个.txt文件,其中包含几行中不同位置的字符。我想读取.txt文件并删除以“:”结尾的行
.txt文件的格式为:
Fruits&Vegetables:
Pearl
Apple
Orange
Grapes: [Green]
Cherry: [Red]
Top 3 Anti-cancer vegetables:
Garlic
Asparagus
Broccoli
Two other fruits:
Banana
Dragon Fruit
我想把它放到一个新的数据框里
Fruits&Veges
Pearl
Apple
Orange
Grapes: [Green]
Cherry: [Red]
Garlic
Asparagus
Broccoli
Banana
Dragon Fruit
我尝试使用.endwith,使用以下代码
import pandas as pd
fruit = pd.Series({'Fruits&Veges':'Pearl'}
file = open('fruit.txt','r')
for line in file:
line = line.rstrip('\n')
if line.endwith(':') == -1:
s = line
else: s = "title"
row = {'Fruits&Veges':s}
fruit = fruit.append(row, ignore_index=True)
fruit = fruit[fruit['Fruits&Veges'] != 'title']
我只想进入一个新的数据帧
Fruits&Veges
Apple
Orange
Grapes: [Green]
Cherry: [Red]
Garlic
Asparagus
Broccoli
Banana
Dragon Fruit
错误信息是'str' object has no attribute 'endwith'
,有什么聪明的方法可以快速完成吗?谢谢你
这次它使用以下代码
相关问题 更多 >
编程相关推荐