Python 3.x 如何从字符串创建一组单词?

Python 3.x 如何从字符串创建一组单词?,python-3.x,Python 3.x,我正在写我的第一个程序 我需要知道如何从字符串创建一组唯一的单词 我想知道如何做到这一点,以便能够知道集合中元素的数量(或字符串中唯一单词的数量) 我需要这样做: ' 输入: 字符串=(“一一二三四你好”) ' 输出: (“一”,“二”,“三”,“四”,“你好”) 字符串具有方法“split”,该方法返回按给定参数拆分的单词列表 string=(“一一二三三四你好”) set_of_words=set(string.split(“”) 输出为: {'three'、'one'、'hello'、'

我正在写我的第一个程序

我需要知道如何从字符串创建一组唯一的单词

我想知道如何做到这一点,以便能够知道集合中元素的数量(或字符串中唯一单词的数量)

我需要这样做:

'

输入:

字符串=(“一一二三四你好”)

'

输出:

(“一”,“二”,“三”,“四”,“你好”)


字符串具有方法“split”,该方法返回按给定参数拆分的单词列表

string=(“一一二三三四你好”)
set_of_words=set(string.split(“”)

输出为:


{'three'、'one'、'hello'、'two'、'four'}

如果您需要保留单词的顺序,请按以下步骤操作:

import collections # OrderedDict is one Python's high-performance containers


string=("one one two three three four hello hello")


unique_word_dict = collections.OrderedDict() # creates and empty ordered dictionary

# The split method of strings breaks the string into parts using the specified separator.
# In this case the separator is a space character so each element in the list is a word.
word_list = string.split(' ') 

# This loops though each element of the list and makes the word a key in the OrderedDict. 
# The .get(word, 0) method creates a new key in the dictionary if it does not already
# exist and initializes it to 0.
# If the key already exists, .get(word, 0) returns the current value.

for word in word_list:
    unique_word_dict[word] = unique_word_dict.get(word, 0) + 1
    print('key: %s, value: %i' % (word, unique_word_dict.get(word)))


unique_words = tuple(unique_word_dict.keys())

print(unique_word_dict)
print(unique_words)
print(len(unique_words))

输出:

key: one, value: 1
key: one, value: 2
key: two, value: 1
key: three, value: 1
key: three, value: 2
key: four, value: 1
key: hello, value: 1
key: hello, value: 2
OrderedDict([('one', 2), ('two', 1), ('three', 2), ('four', 1), ('hello', 2)])
('one', 'two', 'three', 'four', 'hello')
5


欢迎使用stackoverflow。我们很乐意为您提供帮助,但希望看到您迄今为止所做的尝试。若要格式化问题中的代码,请使用三个记号(```)。在编辑问题时,也可以尝试在stack overflow的搜索栏中输入您的问题:“python拆分字符串”和“python数组长度”-也许有人已经回答了。