在python中如何删除以某些字符结尾的行?

2024-09-30 14:20:49 发布

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

我有一个.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',有什么聪明的方法可以快速完成吗?谢谢你


Tags: 文件txtapplelinegreenredcherryfruit
1条回答
网友
1楼 · 发布于 2024-09-30 14:20:49

这次它使用以下代码

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.endswith(':') == False:
       s = line
    else: s = "title"
    row = {'Fruits&Veges':s}
    fruit = fruit.append(row, ignore_index=True)
    fruit = fruit[fruit['Fruits&Veges'] != 'title']

相关问题 更多 >