簡體   English   中英

如何在python中提取和保存字符前后的單詞以及原始字符串

[英]How to extract and save words before & after a character along with the original string in python

這是我需要從中提取的字符串:

Tom and Jerry, Batman and Joker, Homer and Marge

清單還在繼續……這是我希望得到的最終結果(保存為 CSV 或其他格式):

|Tom|
|Jerry|
|Tom and Jerry|
|Batman|
|Joker|
|Batman and Joker|
|Homer|
|Marge|
|Homer and Marge|

我知道我可以使用.split(",")來找到Tom and Jerry ,使用.split("and")來進一步區分湯姆和傑瑞。
但是,我怎樣才能保留所有三個記錄?

謝謝

str.split返回list instance ,而list instance沒有拆分功能。 每個不同的變量都需要利用單個函數的執行結果。

text = "Tom and Jerry, Batman and Joker, Homer and Marge"
result = list()
for text_and in text.split(', '):
    if ' and ' in text_and:  # If 'and' doesn't exist in some of input data,
        for text_name in text_and.split(' and '):
            print(f"|{text_name}|")
            result.append(text_name)
    print(f"|{text_and}|")
    result.append(text_and)
|Tom|
|Jerry|
|Tom and Jerry|
|Batman|
|Joker|
|Batman and Joker|
|Homer|
|Marge|
|Homer and Marge|

這是使用itertools.chain函數的一行代碼。

from itertools import chain
result = list(chain(*[[*text_and.split(' and '), text_and] if ' and ' in text_and else [text_and] for text_and in text.split(', ')]))
# result
['Tom', 'Jerry', 'Tom and Jerry', 'Batman', 'Joker', 'Batman and Joker', 'Homer', 'Marge', 'Homer and Marge']

暫無
暫無

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

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