简体   繁体   English

创建一个接受单词列表的 function,并返回句子中的一组单词

[英]Creating a function that takes a list of words, and return a set of words in the sentence

  1. need to create a function that takes a string需要创建一个带字符串的 function

eg "hello it is a nice day today and it is hot"例如“你好,今天天气很好,很热”

  1. the function needs to use the LIST of words in the string, and create a SET consisting of the words in the string. function 需要使用字符串中单词的 LIST,并创建一个由字符串中的单词组成的 SET。

the output should be: ("hello" "it" "is" "a" "nice" "day" "today" "and" "hot") NOTE: the set only has unique words from the sentence, no repeating words output 应该是:(“hello”“it”“is”“a”“nice”“day”“today”“and”“hot”) 注意:该集合只有句子中的唯一词,没有重复词

I tried it myself but it says its wrong:我自己试过了,但它说错了:

opening_line="It was the best of times, it was the worst of times"

def get_vocabulary(word_list):

  words = word_list.split()

  dickens_words = set()
  dickens_words.add(words)

  return words

print(get_vocabulary(opening_line))

You're adding the entire list as a single element to the set.您将整个列表作为单个元素添加到集合中。 Instead, you could construct a set from list, which would add all the words individually to the set:相反,您可以从列表中构造一个集合,它将所有单词单独添加到集合中:

def get_vocabulary(word_list):
    return set(word_list.split())

The problem is add() accept only one element.问题是 add() 只接受一个元素。

Try adding the link when you create the set创建集合时尝试添加链接

dickens_words = set(words) dickens_words = 设置(单词)

A = list(input("statement:").strip().split(' ')) A = list(input("statement:").strip().split(' '))

print (' '.join(list(dict.fromkeys(A)))) print (' '.join(list(dict.fromkeys(A))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Function 接受一个字母数组,并将它们组合成一个句子中的单词 - Function that takes an array of letters, and combines them into words in a sentence 确定句子中是否包含单词列表? - Determine if a list of words is in a sentence? python用于获取句子列表和单词列表,如果匹配则返回句子的索引 - python for take a list of sentences and a list of words, return the index of the sentence if there is a match 在句子中创建单词及其上下文的字典 - Creating a dictionary of words and their context in a sentence 我想制作一个函数,它接受一个句子并返回一个列表最长的单词以及与最长单词长度相同的单词 - I want to make a function that takes a sentence and returns a list the longest word along with words that have the same length of the longest word 将句子中单词的长度映射到单词列表 - Map length of words in a sentence to a list of words 创建一个函数以返回句子中所有大写的单词(不包括逗号) - Creating a function that returns all capitalized words in a sentence (commas excluded) "给定一个句子,返回一个单词颠倒的句子" - Given a sentence, return a sentence with the words reversed 提取带有单词列表的完整句子 - Extract full sentence with list of words 是否有用于将句子拆分为单词列表的库? - Is there a library for splitting sentence into a list of words in it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM