【问题标题】:Alternating Words in Strings- Python字符串中的交替单词 - Python
【发布时间】:2013-01-10 02:08:53
【问题描述】:

我必须创建一个程序,要求用户输入两个字符串,然后 生成一个新字符串,从第一个字符串中交替一个单词 和第二个字符串中的一个单词,其中“单词”如上所述定义为空格或标点符号之间的任何内容。什么时候 一个字符串用完了单词,只需使用较长字符串的其余部分。 (例如,“This.is.a, test”和“我妈妈做的意大利面 酱”将产生“这是我的妈妈,使测试成为平均意大利面 酱’)

任何输入将不胜感激我正在尝试学习如何编程,而我目前所拥有的根本不起作用。

【问题讨论】:

  • 嗯,你需要指定语言。不同编程语言之间的字符串处理差异很大。但是,一般来说,您需要先根据分隔字符“,.?!”拆分每个字符串,然后同时循环它们。

标签: python string list alternate


【解决方案1】:

查看 Python 的 itertools 模块的文档。特别是 itertools.izip_longest 函数(解决您发布的确切问题)。

来自文档:

itertools.izip_longest(*iterables[, fillvalue]) 创建一个迭代器,聚合来自每个可迭代对象的元素。如果可迭代的长度不均匀,则用 fillvalue 填充缺失值。迭代一直持续到最长的可迭代对象用完为止。

如果其中一个 iterables 可能是无限的,那么 izip_longest() 函数应该用一些限制调用次数的东西来包装(例如 islice() 或 takewhile())。如果没有指定,fillvalue 默认为 None。

【讨论】:

    【解决方案2】:

    random 模块是一个很好的模块,可以帮助解决这个问题。

    我使用string 模块来删除所有的标点符号。

    import random
    import string
    sentence_one = raw_input('Enter the first sentence! ').translate(None, string.punctuation)
    sentence_two = raw_input('Enter the second sentence! ').translate(None, string.punctuation)
    mylist1 = sentence_one.split()
    mylist2 = sentence_two.split()
    mylist3 = mylist1 + mylist2
    random.shuffle(mylist3)
    randomsentence = ' '.join(mylist3)
    print randomsentence
    

    运行时:

    Enter the first sentence! one, two, three
    Enter the second sentence! four! five! six!
    three two four six one five # Well it could be anything really, this is randomised.
    

    【讨论】:

      猜你喜欢
      • 2014-04-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      • 2018-05-31
      相关资源
      最近更新 更多