如果你的INP UT文件是由發件人行列表行:
ATamsterdam_lady tweeted: ATrvanbommel ja dikke vlokken
ATKoningsbruggen tweeted: ATCGCommunicatie zitten jullie in Amsterdam?
ATJustoRasta tweeted: febovers ... AT Leidseplein - Amsterdam Centrum t.co/KCUCzj2dWq
AT7Ash_bash tweeted: #HENNY AND AMSTERDAM TONIGHT
那麼你可以使用下面的Python代碼:
input_file = 'twitter.txt'
output_file = 'result.txt'
keyword = 'Amsterdam'
with open(input_file) as f:
lines = f.readlines()
for line in lines:
message = line.split('tweeted: ')[1]
if keyword.lower() in message.lower():
with open(output_file, 'a') as myfile:
myfile.write(line)
生成的輸出文件包含行文字行與包括「阿姆斯特丹」只有在'消息'部分:
ATKoningsbruggen tweeted: ATCGCommunicatie zitten jullie in Amsterdam?
ATJustoRasta tweeted: febovers ... AT Leidseplein - Amsterdam Centrum t.co/KCUCzj2dWq
AT7Ash_bash tweeted: #HENNY AND AMSTERDAM TONIGHT
*如何使用Python代碼刪除後一行?*是的,您可以。嘗試編寫一個讀取數據的腳本,並且當您在過濾器行上卡住時,會返回一個新問題。 – 2015-02-23 14:28:27
[打開文件並迭代它](https://docs.python.org/2.7/tutorial/inputoutput.html#reading-and-writing-files),['''split'''](https: //docs.python.org/2.7/library/stdtypes.html#str.split)冒號的每一行(''':'''),['''if'''](https:// docs .python.org/2.7/tutorial/controlflow.html#if-statements)該行符合您的標準,[保存在列表中](https://docs.python.org/2.7/tutorial/introduction.html#lists ) – wwii 2015-02-23 14:31:10