Python 更换和储存

Python 更换和储存,python,replace,store,file-handling,Python,Replace,Store,File Handling,那么,我得到的是: 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 entere

那么,我得到的是:

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()等将句子等存储到文件中


谢谢

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

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

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

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
另外,在代码中,当您在“GetSession”中调用“GetSession”时,您应该返回其返回值:

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:
    ...

你没有说你有什么问题。问题是什么?在你的
单词列表中有两次“world”,但在代码中你试图避免它,对吗?从单词到数字的赋值应该是自动的吗?replace函数到底要做什么?与今天早些时候提出的问题几乎相同。也应该是
1231
?哈哈,对不起,是的,这有点慢。如果您已经在构建一系列独特的单词,只需执行
枚举(单词)
。如果要丢弃字母,则
next(zip(*enumerate(words))
works这不需要是唯一的序列…因此这与构建唯一序列然后使用enumerate right相同,但它也是O(n^2).
str.index
是出了名的慢。我不会在任何超过100个单词的字符串上使用它。谢谢,但是你去掉标点符号的部分给了我一个错误:
回溯(最后一次调用):
文件“C:/Python33/j.py”,第4行,在
句子.translate(str.maketrans)中(无,无,字符串.标点符号)
类型错误:必须是str,而不是None
@OllieMills啊,是的,它需要空字符串而不是
s。我的错误。修复了。好的,这样做很好。我大致知道如何做,但我需要程序记住这些值。例如,如果用户输入值:“Hello world said Hello”如果我想回忆它们,程序会将它们存储为2 1 1 0 2,我可以输入2 1 0 2,程序会发出“Hello world world said Hello”的声音,我不想听起来好像我要让你为我做这一切,但我需要将值放入文件并从文件中读取;这有点超出我的能力:)@OllieMills那么,你应该考虑使用
pickle
来存储替换字典。如果你不能理解它,那就值得再问一个问题。你不应该以这种方式为用户输入重新编译。当你真的不需要递归函数时,它会创建一个递归函数。使用无限循环(
while True
)最后进行验证。
break
如果输入有效。@Adam,你是对的,你应该验证输入并再次询问正确答案。我刚刚看到他再次调用GetSession函数而没有返回,所以我对此进行了评论。无论如何,在这种情况下,递归只会发生几次最多(好吧,一个用户可以输入错误的输入多少次?)这不应该是个问题,但我同意这是不必要的,在其他情况下可能是个问题。我发布这篇文章的另一个原因是因为我认为Python有尾部调用递归,我现在意识到它没有(没有解决方法),所以谢谢。