所以,这就是我得到的:
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"]
并使每个单词都有一个数字:
所以,让我们说“你好”的值为1,句子将是'1世界世界说1'
如果世界是2,那将是'1 2 2说1' 最后,如果“说”是3,那将是'1 2 2 1 2'
我们将非常感谢任何帮助,然后我将开发此代码,以便使用file.write()
和file.read()
等将句子等存储到文件中
感谢
答案 0 :(得分:0)
这些单词变成数字的顺序是否重要? 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
答案 1 :(得分:0)
如果您只想要每个单词所在的位置
positions = map(words.index,words)
此外,切勿为变量或函数使用内置函数名称。并且永远不要将变量与函数(replace = replace(...)
)相同,函数是对象
编辑:在python 3中,您必须将地图返回的迭代器转换为列表
positions = list(map(words.index, words))
或使用理解列表
positions = [words.index(w) for w in words]
答案 2 :(得分:0)
另一个想法(尽管不认为它比其他想法更好),使用词典:
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:
...