【问题标题】:Elegant way for creating a narrative string of a list创建列表叙述字符串的优雅方式
【发布时间】:2014-04-26 21:23:12
【问题描述】:

您如何优雅地将具有未知数量元素的列表转换为用户界面的叙述性文本表示?

例如:

>>> elements = ['fire', 'water', 'wind', 'earth']

>>> narrative_list(elements)
'fire, water, wind and earth'

【问题讨论】:

  • 这正是您想要的吗?逗号和末尾的 and 词?

标签: python string nlp


【解决方案1】:
def narrative_list(elements):
    last_clause = " and ".join(elements[-2:])
    return ", ".join(elements[:-2] + [last_clause])

然后像这样运行

>>> narrative_list([])
''
>>> narrative_list(["a"])
'a'
>>> narrative_list(["a", "b"])
'a and b'
>>> narrative_list(["a", "b", "c"])
'a, b and c'

【讨论】:

    【解决方案2】:
    def narrative_list(elements):
        """
        Takes a list of words like: ['fire', 'water', 'wind', 'earth']
        and returns in the form: 'fire, water, wind and earth'
        """
        narrative = map(str, elements)
    
        if len(narrative) in [0, 1]:
            return ''.join(narrative)
    
        narrative.append('%s and %s' % (narrative.pop(), narrative.pop()))    
        return ', '.join(narrative)
    

    【讨论】:

    • 很好的解决方案,但这不适用于 map 返回生成器的 python3。代替map,使用[str(e) for e in elements]
    【解决方案3】:

    在 python 中有非常(非常)经常存在的库来做你想做的事。查看人性化https://pypi.python.org/pypi/humanfriendly/1.7.1

    >>> import humanfriendly
    >>> elements = ['fire', 'water', 'wind', 'earth']
    >>> humanfriendly.concatenate(elements)
    'fire, water, wind and earth'
    

    如果你做了很多人性化,我只会打扰这个。否则我喜欢 Hugh Bothwell 的回答(因为它消除了代码中的第三方依赖)。

    【讨论】:

      【解决方案4】:
      >>> ', '.join(elements[:-1])+' and '+elements[-1]
      'fire, water, wind and earth'
      

      编辑:这适用于二元素列表,但您可能需要一元素列表(或空列表)的特殊情况

      【讨论】:

      • 注意:您可能希望特殊情况下非常短的列表(少于两个元素)。
      【解决方案5】:
      >>> elements = ['fire', 'water', 'wind', 'earth']
      >>> ", ".join(elements)[::-1].replace(' ,', ' dna ',1)[::-1]
      'fire, water, wind and earth'
      >>> elements = ['fire']
      >>> ", ".join(elements)[::-1].replace(' ,', ' dna ',1)[::-1]
      'fire'
      >>> elements = ['fire', 'water']
      >>> ", ".join(elements)[::-1].replace(' ,', ' dna ',1)[::-1]
      'fire and water'
      

      【讨论】:

      • 如果元素包含逗号,它将失败。
      • 当元素在单词末尾包含逗号时会失败,如果单词包含空格也会失败
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 2020-09-04
      相关资源
      最近更新 更多