簡體   English   中英

如何讀取一行並忽略一些單詞(python)

[英]how to read a line and ignore some words (python)

我正在逐行讀取文本文件,我想忽略所有出現的“和”,“收件人”和“發件人”並返回其余部分。 python中有一個函數可以讓我這樣做嗎? 謝謝你的幫助。

使用替換或拆分空格中的線並重新組裝而不使用您不需要的單詞,例如:

In [6]: testsrt = 'I\'m reading a text file line by line and i want to ignore all occurrences of and , To and From and return the rest. Is there a function in python that will allow me to do that? Thanks for your help.'

In [7]: ts = testsrt.split(' ')                                                                                                                                                                                                                   

In [8]: excl = ["and", "To", "From"]                                                                                                                                                                                                              

In [9]: ' '.join([t for t in ts if not t in excl])                                                                                                                                                                                                
Out[9]: "I'm reading a text file line by line i want to ignore all occurrences of , return the rest. Is there a function in python that will allow me to do that? Thanks for your help."                                                          

請注意,如果您保留引號,則不會刪除單詞,因為這是逐字工作的。

您還可以將re.replace視為一種繼續進行的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM