問題描述
更換和存放 (Replacing and Storing)
所以,這就是我得到的:
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 world 說 1'
如果 world 是 2,那將是 '1 2 2 say 1' 最後,如果“said”是 3,那將是 '1 2 2 1 2'
任何幫助將不勝感激,然後我將開發此代碼,以便使用 file.write()
和 file 將句子等存儲到文件中。 read()
等
謝謝
參考解法
方法 1:
Does it matter what order the words are turned into numbers? Is Hello
and hello
two words or one? Why not something like:
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
方法 2:
If you want just the position in which each word is you can do
positions = map(words.index,words)
Also, NEVER use built‑in function names for your variables or functions. And also never call your variables the same as your functions (replace = replace(...)
), functions are objects
Edit: In python 3 you must convert the iterator that map returns to a list
positions = list(map(words.index, words))
Or use a comprehension list
positions = [words.index(w) for w in words]
方法 3:
Another idea (although don't think it's better than the rest), use dictionaries:
dictionary = dict()
for word in words:
if word not in dictionary:
dictionary[word] = len(dictionary)+1
Also, on your code, when you're calling "getSentence" inside "getSentence", you should return its return value:
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:
...
(by Ollie Mills、Adam Smith、Mr. E、tglaria)