简体   繁体   English

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

[英]How to remove lines end with certain characters in python?

I have a.txt file which contains several characters in different position in lines.我有一个 .txt 文件,其中包含行中不同 position 中的几个字符。 I want to read the.txt file and remove those lines end with ":"我想阅读 .txt 文件并删除那些以“:”结尾的行

The format of.txt file is: .txt文件的格式为:

Fruits&Vegetables:
Pearl 
Apple 
Orange 
Grapes: [Green] 
Cherry: [Red] 
Top 3 Anti-cancer vegetables:
Garlic 
Asparagus 
Broccoli 
Two other fruits:
Banana 
Dragon Fruit

I want to get this in a new dataframe我想在新的 dataframe 中得到这个

Fruits&Veges 
Pearl         
Apple         
Orange        
Grapes: [Green] 
Cherry: [Red] 
Garlic        
Asparagus     
Broccoli      
Banana        
Dragon Fruit 

I have tried to use.endwith, with following code.我尝试使用.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']

I simply want to get in a new dataframe我只是想买一个新的 dataframe

Fruits&Veges
Apple
Orange
Grapes: [Green]
Cherry: [Red]
Garlic
Asparagus
Broccoli
Banana
Dragon Fruit

The error message is 'str' object has no attribute 'endwith' , is there any smart way to do it quickly?错误信息是'str' object has no attribute 'endwith' ,有什么聪明的方法可以快速做到吗? Thank you.谢谢你。

It works with the following code this time...这次它使用以下代码......

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM