更換和存放 (Replacing and Storing)


問題描述

更換和存放 (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 MillsAdam SmithMr. Etglaria)

參考文件

  1. Replacing and Storing (CC BY‑SA 2.5/3.0/4.0)

#file-handling #Python #store #replace






相關問題

c語言使用文件操作創建數據庫 (Create database using file operation in c language)

使用jsp瀏覽文件和文件夾 (browsing files and folders using jsp)

在 rails/paperclip 中處理一系列圖像 (handling an array of images in rails/paperclip)

Java 並行文件處理 (Java Parallel File Processing)

Perl 隱式關閉重置 $. 多變的 (Perl implicit close resets the $. variable)

更換和存放 (Replacing and Storing)

逐行讀取文件並基於它將換行符寫入同一文件 - nodejs (Reading a file line by line and based on it write newlines to same file - nodejs)

使用 PHP 將數據放到服務器上(新的 DOMdocument 不起作用) (Use PHP to put data onto server ( new DOMdocument not working))

表示“目錄”或“文件”的詞是什麼? (What is the word that means "directory" or "file"?)

如何在我的計算機上保存我用 Python 編輯的 CSV 文件? (How do I save a CSV file on my computer which i have edited in Python?)

使用文件中的類和對象獲取信息 (Get info using class and object from file)

使用 putw() 時在文件中獲取亂碼 (Getting gibberish values in files when putw() is used)







留言討論