[英]How to retain delimiter within list item python
我正在編寫一個程序,該程序使用標點符號作為何時拆分文本的分隔符來混淆文本中的子句。
目前我的代碼有一個很大的列表,其中每個項目都是一組子句。
import re
from random import shuffle
clause_split_content = []
text = ["this, is. a test?", "this: is; also. a test!"]
for i in text:
clause_split = re.split('[,;:".?!]', i)
clause_split.remove(clause_split[len(clause_split)-1])
for x in range(0, len(clause_split)):
clause_split_content.append(clause_split[x])
shuffle(clause_split_content)
print(*content, sep='')
目前結果使文本混亂而不保留用作分隔符的標點符號來拆分它。 output 是這樣的:
a test this also this is a test is
我想在最后的 output 中保留標點符號,所以它看起來像這樣:
a test! this, also. this: is. a test? is;
選項1:將每個索引中的單詞打亂並組合成句子。
from random import shuffle
count = 0
sentence = ''
new_text = []
text = ["this, is. a test?", "this: is; also. a test!"]
while count < len(text):
new_text.append(text[count].split())
shuffle(new_text[count])
count += 1
for i in new_text:
for j in i:
sentence += j + ' '
print(sentence)
樣本洗牌輸出:
test? this, a is. is; test! this: a also.
test? a is. this, is; test! a this: also.
is. test? a this, test! a this: also. is;
選項2:將列表中的所有元素組合成一個元素,然后打亂單詞並組合成一個句子。
import random
from random import shuffle
count = 0
sentence = ''
new_text = []
text_combined = []
text = ["this, is. a test?", "this: is; also. a test!"]
while count < len(text):
new_text.append(text[count].split())
count += 1
for i in new_text:
for j in i:
text_combined.append(j)
shuffled_list = random.sample(text_combined, len(text_combined))
for i in shuffled_list:
sentence += i + ' '
print(sentence)
樣本輸出:
this, is; also. a this: is. a test? test!
test! is. this: test? a this, a also. is;
is. a a is; also. test! test? this, this:
我認為您只是出於您的目的使用了錯誤的re
功能。 split()
不包括您的分隔符,但您可以使用另一個函數,例如findall()
手動選擇您想要的所有單詞。 例如,使用以下代碼,我可以創建您想要的輸出:
import re
from random import shuffle
clause_split_content = []
text = ["this, is. a test?", "this: is; also. a test!"]
for i in text:
words_with_seperator = re.findall(r'([^,;:".?!]*[,;:".?!])\s?', i)
clause_split_content.extend(words_with_seperator)
shuffle(clause_split_content)
print(*clause_split_content, sep=' ')
輸出:
this, this: is. also. a test! a test? is;
模式([^,;:".?!]*[,;:".?!])\s?
只取所有不是分隔符的字符,直到看到分隔符。 這些字符都在匹配組中,這會創建您的結果。 \s?
只是為了擺脫單詞之間的空格字符。
這是一種執行您所要求的方法:
import re
from random import shuffle
text = ["this, is. a test?", "this: is; also. a test!"]
content = [y for x in text for y in re.findall(r'([^,;:".?!]*[,;:".?!])', x)]
shuffle(content)
print(*content, sep=' ')
輸出:
is; is. also. a test? this, a test! this:
解釋:
r'([^,;:".?!]*[,;:".?!])'
匹配 0 個或多個非分隔符后跟一個分隔符,並且findall()
返回一個列表所有此類非重疊匹配text
中的輸入字符串,並有一個內部循環迭代每個輸入字符串的findall
結果,因此我們為每個字符串中的每個匹配模式創建一個列表。shuffle
和print
與您的原始代碼一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.