簡體   English   中英

刪除字符串中第一次出現的單詞

[英]Remove first occurrence of word in string

test = 'User Key Account Department Account Start Date'

我想從字符串中刪除重復的單詞。 這個問題的解決方案運行良好......

def unique_list(l):
     ulist = []
     [ulist.append(x) for x in l if x not in ulist]
     return ulist

test = ' '.join(unique_list(test.split()))

但它只保留后續的重復項。 我想刪除字符串中的第一次出現,以便測試字符串讀取“用戶密鑰部門帳戶開始日期”。

這應該可以完成這項工作:

test = 'User Key Account Department Account Start Date'

words = test.split()

# if word doesn't exist in the rest of the word list, add it
test = ' '.join([word for i, word in enumerate(words) if word not in words[i+1:]])

print(test)  # User Key Department Account Start Date

如果您只想保留每個單詞的最后一次出現,那么只需從后面開始並繼續前進。

tokens = test.split()
final = []

for word in tokens[::-1]:
    if word in final:
        continue
    else:
        final.append(word)

print(" ".join(final[::-1]))
>> 'User Key Department Account Start Date'

這是一種方法:

l=test.split()
m=set([i for i in l if test.count(i)>1])

for i in m:
    l.remove(i)

res = ' '.join(l)

>>> print(res)
'User Key Department Account Start Date'

您可以將源字符串轉換為列表,然后在使用unique_list函數之前反轉列表,然后在轉換回字符串之前再次反轉列表。

def unique_list(l):
     ulist = []
     [ulist.append(x) for x in l if x not in ulist]
     return ulist


orig="User Key Account Department Account Start Date"
orig_list=orig.split()
orig_list.reverse()

uniq_rev=unique_list(orig_list)
uniq_rev.reverse()

print(orig)
print(' '.join(uniq_rev))

例子:

$ python rev.py 
User Key Account Department Account Start Date
User Key Department Account Start Date

如果你喜歡它的功能:

from functools import reduce
from collections import Counter

import re


if __name__ == '__main__':
    sentence = 'User Key Account Department Account Start Date'

    result = reduce(
        lambda sentence, word: re.sub(rf'{word}\s*', '', sentence, count=1),
        map(
            lambda item: item[0],
            filter(
                lambda item: item[1] > 1,
                Counter(sentence.split()).items()
            )
        ),
        sentence
    )

    print(result)
    # User Key Department Account Start Date

將所有元素放入一個集合中。

將您的句子標記為字符串並插入到集合中。

set<std::string> s;

s.insert("aa");
s.insert("bb");
s.insert("cc");
s.insert("cc");
s.insert("dd");

暫無
暫無

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

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