【问题标题】:How to print unique words from an inputted string如何从输入的字符串中打印唯一的单词
【发布时间】:2017-03-16 08:21:30
【问题描述】:

我有一些代码,我打算打印出用户输入的字符串中的所有唯一单词:

str1 = input("Please enter a sentence: ")

print("The words in that sentence are: ", str1.split())

unique = set(str1)
print("Here are the unique words in that sentence: ",unique)

我可以让它打印出唯一的字母,但不能打印出唯一的单词。

【问题讨论】:

  • 只需将分割后的字符串传给set:set(str1.split())
  • 谢谢你,真的有帮助! ;)

标签: python string set python-3.5


【解决方案1】:

另外,您可以使用:

from collections import Counter

str1 = input("Please enter a sentence: ")
words = str1.split(' ')
c = Counter(words)
unique = [w for w in words if c[w] == 1]

print("Unique words: ", unique)

【讨论】:

    【解决方案2】:

    String.split(' ') 接受一个字符串并创建一个由空格分隔的元素列表 (' ')。

    set(foo) 接受一个集合 foo 并返回一个 set 集合,该集合仅包含 foo 中的不同元素。

    你想要的是这个:unique_words = set(str1.split(' '))

    分割分隔符的默认值为空格。我想表明你可以为这个方法提供你自己的价值。

    【讨论】:

    • 实际上split 的默认值是 any 空格一起,这是一个重要的区别:' '.split(' ') == ['','']' '.split() == []
    • 是的,我刚才修改了。感谢您指出。 ;) 似乎它也删除了尾随和前导空格。好奇。
    • 是的,正如我所料,只是一个简单的补充。谢谢您的帮助! ;)
    猜你喜欢
    • 2023-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 2017-04-15
    • 1970-01-01
    • 2019-03-14
    • 2020-01-22
    相关资源
    最近更新 更多