繁体   English   中英

Python条件列表连接

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM