更换和储存

2024-04-26 08:02:49 发布

您现在位置:Python中文网/ 问答频道 /正文

那么,我得到的是:

def getSentence():

  sentence = input("What is your sentence? ").upper()

  if sentence == "":
    print("You haven't entered a sentence. Please re-enter a sentence.")
    getSentence()
  elif sentence.isdigit():
    print("You have entered numbers. Please re-enter a sentence.")
    getSentence()
  else:
    import string
    for c in string.punctuation:
      sentence = sentence.replace(c,"")
      return sentence

def list(sentence):

  words = []
  for word in sentence.split():
    if not word in words:
      words.append(word)
    print(words)

def replace(words,sentence):
  position = []
  for word in sentence:
    if word == words[word]:
      position.append(i+1)
      print(position)

sentence = getSentence()
list = list(sentence)
replace = replace(words,sentence)

我只想做到这一点,我的全部意图是把这个句子,分成几个单词,把每个单词变成一个数字

words = ["Hello","world","world","said","hello"]

使每个单词都有一个数字:

所以,假设“hello”的值为1,句子将是“1 world said 1”

如果世界是2,那就是“12说1”
最后,如果“said”是3,那就是“12”

如果有任何帮助,我将非常感谢,然后我将开发此代码,以便使用file.write()file.read()等将句子等存储到文件中

谢谢


Tags: inforworldifdefposition单词sentence
3条回答

如果你只想知道每个单词的位置,你可以做到

positions = map(words.index,words)

另外,不要对变量或函数使用内置函数名。也不要像调用函数一样调用变量(replace = replace(...)),函数是对象

编辑:在Python3中,必须将映射返回的迭代器转换为列表

positions = list(map(words.index, words))

或者使用理解列表

positions = [words.index(w) for w in words]

另一个想法(尽管不认为它比其他的好),使用字典:

dictionary = dict()
for word in words:
    if word not in dictionary:
        dictionary[word] = len(dictionary)+1

另外,在代码中,当您在“getSentence”中调用“getSentence”时,应该返回其返回值:

if sentence == "":
    print("You haven't entered a sentence. Please re-enter a sentence.")
    return getSentence()
elif sentence.isdigit():
    print("You have entered numbers. Please re-enter a sentence.")
    return getSentence()
else:
    ...

单词变成数字的顺序重要吗?Hellohello是两个词还是一个词?为什么不这样做:

import string

sentence = input()  # user input here
sentence.translate(str.maketrans('', '', string.punctuation))
# strip out punctuation

replacements = {ch: str(idx) for idx, ch in enumerate(set(sentence.split()))}
# builds {"hello": 0, "world": 1, "said": 2} or etc

result = ' '.join(replacements.get(word, word) for word in sentence.split())
# join back with the replacements

相关问题 更多 >