Python:Want 删除包含特定单词的行

Python:Want to remove the line that contain specific word

from lxml import html
import requests
import csv
page = requests.get('http://www.google.com/finance?q=[%28exchange+%3D%3D+%22ABC%22%29]&restype=company&noIL=1&start=0&num=1500')
tree = html.fromstring(page.content)

#Scrape stocks companies and symbols

stocks = tree.xpath('//a [not(@class)][@id][@href]/text()')
#This will create a list of prices
stocks.remove('IRM Group Berhad');
stocks.remove('A & M Realty Berhad');
stocks.remove('BERJAYA FOOD BERHAD- A SHARES');


print 'Stocks= ', stocks

# open a file for writing.
csv_out = open('KLSE.csv', 'wb')

mywriter = csv.writer(csv_out)

rows = zip(stocks)
mywriter.writerows(rows)

csv_out.close()

我想删除所有包含单词 'Berhad' 的行,因为我不想将其一一删除。知道怎么做吗?

假设股票只是一个普通列表,您可以尝试类似

trimmed_stocks = [ x for x in stocks if not 'Berhad' in x ]

从您的 post 中不清楚是否也应该排除 BERHAD 或 bErHaD,但可以类似地处理它们。

你可以这样做:

stocks = [s for s in stocks if 'berhad' not in s.lower()]