[英]Python conditional list joins
我有一個如下所示的列表:
[
'A',
'must',
'see',
'is',
'the',
'Willaurie',
',',
'which',
'sank',
'after',
'genoegfuuu',
'damaged',
'in',
'a',
'storm',
'in',
'1989',
'.'
]
如你所見,有標點符號。 我想使用空格來調用.join
除了字符串是標點符號的情況,然后我不想要分隔符。
最好的方法是什么?
我已經嘗試了一段時間,我的解決方案變得過於復雜,似乎是一個簡單的任務。
謝謝
string
模塊有一個包含所有標點字符的列表。
import string
string = ''.join([('' if c in string.punctuation else ' ')+c for c in wordlist]).strip()
你已經得到了答案,但只是想補充一點,並非所有的標點符號都應該放在左側。 如果你想處理更一般的句子,你可以有例如括號或撇號,你不想最終得到類似的東西:
這是一部很棒的電影(我見過最好的)
我會說創造一些令人討厭的單線是沒有意義的,只是為了以大多數pythonic的方式做到這一點。 如果您不需要超快速解決方案,可以考慮逐步解決,例如:
import re
s = ['It', "'", 's', 'a', 'great', 'movie',
'(', 'best', 'I', "'", 've', 'seen', ')']
s = " ".join(s) # join normally
s = re.sub(" ([,.;\)])", lambda m: m.group(1), s) # stick to left
s = re.sub("([\(]) ", lambda m: m.group(1), s) # stick to right
s = re.sub(" ([']) ", lambda m: m.group(1), s) # join both sides
print s # It's a great movie (best I've seen)
它非常靈活,您可以指定每個規則處理哪個標點符號...雖然有4行,但您可能不喜歡它。 無論你選擇哪種方法,都可能會有一些句子無法正常工作並且需要特殊情況,所以無論如何,單行可能只是一個糟糕的選擇。
編輯:實際上,您可以將上述解決方案收縮到一行,但如前所述,我很確定還有更多需要考慮的案例:
print re.sub("( [,.;\)]|[\(] | ['] )", lambda m: m.group(1).strip(), " ".join(s))
>>> ''.join([('' if i in set(",.!?") else ' ') + i for i in words]).strip()
'A must see is the Willaurie, which sank after genoegfuuu damaged in a storm in 1989.'
像這樣
re.sub(r'\s+(?=\W)', '', ' '.join(['A', 'must', 'see', 'is', 'the', 'Willaurie', ',', 'which', 'sank', 'after', 'genoegfuuu', 'damaged', 'in', 'a', 'storm', 'in', '1989', '.']))
使用過濾器怎么樣?
words = ['A', 'must', 'see', 'is', 'the', 'Willaurie', ',', 'which', 'sank', 'after', 'genoegfuuu', 'damaged', 'in', 'a', 'storm', 'in', '1989', '.']
' '.join(filter(lambda x: x not in string.punctuation, words))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.