我有一个标记句子的列表,例如:
text = ['Selegiline',
'-',
'induced',
'postural',
'hypotension',
'in',
'Parkinson',
"'",
's',
'disease',
':',
'a',
'longitudinal',
'study',
'on',
'the',
'effects',
'of',
'drug',
'withdrawal',
'.']我想将这个列表转换成一个字符串,但是当出现像-或:这样的标点符号时,我希望删除额外的空间,所以最后的输出如下所示:
Selegiline-induced postural hypotension in Parkinson's disease: a longitudinal study on the effects of drug withdrawal我尝试将列表分割成相等的块,并检查两个对象对是否是单词,然后使用单个空格;否则,没有空格:
def chunks(xs, n):
n = max(1, n)
return (xs[i:i+n] for i in range(0, len(xs), n))
data_first = list(chunks(text, 2))
def check(data):
second_order = []
for words in data:
if all(c.isalpha() for c in words[0]) and all(c.isalpha() for c in words[1]):
second_order.append(" ".join(words))
else:
second_order.append("".join(words))
return second_order
check(data_first)但我必须将其迭代到最后一个字(递归解决方案)。有更好的方法吗?
发布于 2022-09-20 18:30:49
一种选择可能是创建标点符号和替换字符串的字典,因为每个标点符号似乎遵循不同的规则(冒号应该保留本身之后的空格,其中破折号不应该保留)。
类似于:
punctdict={' - ':'-',' : ':': '," ' ":"'"}
sentence=' '.join(text)
for k,v in punctdict.items():
sentence = sentence.replace(k, v)发布于 2022-09-20 18:52:28
text = ['Selegiline',
'-',
'induced',
'postural',
'hypotension',
'in',
'Parkinson',
"'",
's',
'disease',
':',
'a',
'longitudinal',
'study',
'on',
'the',
'effects',
'of',
'drug',
'withdrawal',
'.']
def txt_join(txt):
ans=""
for s in txt:
if(s==".") or (s==":"):
ans=ans.strip()+s+" "
elif s=="'" or (s=="-"):
ans=ans.strip()+s
else:
ans=ans+s+" "
return ans
print(txt_join(text))据我所知,这将给你预期的结果。在这个阿尔法里。它通过文本列表进行规范化循环,并根据标点符号添加空格(根据标点符号必须添加if/elif/ add条件)。
https://stackoverflow.com/questions/73791051
复制相似问题