簡體   English   中英

從python中的一長串字符串中查找並刪除一些子字符串

[英]find and remove some substrings from a long list of string in python

我需要閱讀字符串列表並刪除一些特殊字符。 我編寫了有效的代碼,但我正在尋找一種有效編寫此代碼的方法。因為,我需要對一百萬個長列表(例如,每個列表有100000個單詞)執行此過程。

我寫了例子來澄清我的問題。

input:
 str= ['short', 'club', 'edit', 'post\C2', 'le\C3', 'lundi', 'janvier', '2008'] 
 specialSubString=['\C2','\C3','\E2'] 

output:
 str= ['short', 'club', 'edit', 'post', 'le', 'lundi', 'janvier', '2008'] 

我的代碼:

ml=len(str)
for w in range(0,ml):
   for i in range(0, len(specialSubString)):
       token=specialSubString[i]
       if token not in str[w]: 
          continue
       else:
          l= len(token)
          t= str[w]
          end= len(t)-l
          str[w]=t[:end]
          break

for w in str:
    print w

創建一個包含所有要刪除的特殊字符的字符串,並將其從右側剝離

strings = ['short', 'club', 'edit', 'post\C2', 'le\C3', 'lundi', 'janvier', '2008']
special = ''.join(['\C2','\C3','\E2']) # see note

請注意,此時\\是一個特殊字符,使用時應將其轉義,以免產生歧義。 您也可以簡單地創建字符串文字,而不是使用str.join

special = '\\C2\\C3\\E2' # that's better

strings[:] = [item.rstrip(special) for item in strings]

暫無
暫無

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

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