簡體   English   中英

如果字符串包含特定字符,如何從字符串中刪除單詞?

[英]How to remove word from a string if it contains a specific character?

好的,假設我的字符串包含以下內容: "$$$FOOD WATERMELON" 如何從字符串中刪除"$$$FOOD"

假設我在列表中有字符串:

data_list = ["$$$FOOD WATERMELON", "$$$STORY I walked to the local store"]

我在代碼中的方法拆分列表中的元素,然后遍歷列表內的列表並刪除任何包含"$$$"元素,如果不是因為.split()函數拆分每個單詞,因此列表最終將如下所示: [["WATERMELON"],["I","walked","to","the","local,"store"]]這不是最優的,因為那樣我將不得不加入列表中的元素,這需要更多的時間。

基本上,我唯一想知道的是:如果字符串中包含"$$$"我該如何刪除它。 所以這個字符串: word = "$$$STORY I walked to the store"將變成"I walked to the store"

對不起,如果這令人困惑

你可以試試這個:

>>> word = "$$$STORY I walked to the store"
>>> if word.startswith('$',0,word.index(' ')):
        word=word[word.index(' ')+1:]

>>> word
'I walked to the store'

以下是使用列表和函數的外觀:


def check_word(word):
    if word.startswith('$',0,word.index(' ')):
        return word[word.index(' ')+1:]
data_list = ["$$$FOOD WATERMELON", "$$$STORY I walked to the local store"]
list2=[check_word(x) for x in data_list]
print(list2)

試試這個。

import re

data_list = ["$$$FOOD WATERMELON", "$$$STORY I walked to the local store"]
output = [re.sub(r'\s*[$]+\w+\s*', '', x) for x in data_list]

這給了我以下輸出:

['WATERMELON', 'I walked to the local store']

這是正則表達式定義:

\s
matches any whitespace character (equivalent to [\r\n\t\f\v ])
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Match a single character present in the list below [$]
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
$ matches the character $ with index 3610 (2416 or 448) literally (case sensitive)
\w
matches any word character (equivalent to [a-zA-Z0-9_])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
\s
matches any whitespace character (equivalent to [\r\n\t\f\v ])
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)

此代碼檢查並確保任何單詞都沒有子字符串,而不僅僅是像其他一些答案一樣的第一個單詞。

輸出:

['WATERMELON', 'I walked to the local store']

代碼:

data_list = ["$$$FOOD WATERMELON", "$$$STORY I walked to the local store"]

for word in range(len(data_list)):
  temp1 = data_list[word].split(" ")
  finished = False
  while not (finished):
      for temp2 in range(len(temp1)):
          if "$$$" in temp1[temp2]:
              temp1.pop(temp2)
              break
          finished = True
  data_list[word] = ' '.join(temp1)

print(data_list)

暫無
暫無

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

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