我是一個初學者 python 程式員和這個論壇網站的新手。我四處尋找,但無法找到我一直在尋找的東西,所以我來到了這里。
我有一個函式可以計算用戶輸入給出的兩個值之間的百分比誤差,將該值寫入字串中的檔案:'Trial x % error = y',其中 x 是試用號,y 等于浮點值百分比誤差。每次運行此函式時,它都會在檔案中添加一個新行并寫入“Trial (x 1) % error = y”,這樣可以輕松跟蹤您的試驗。然后該函式將檔案中的每一行轉換為串列的屬性,并將該串列中的最后一項列印到控制臺。
為了解決這個問題,我決定這樣做的一種方法是:將串列中的每個屬性(這是一個單詞字串)拆分為空格,并將一行中的每個單詞保存到它自己的串列中。這樣我就可以索引新串列中的第二個屬性并將其保存為值 x,將其加 1,這將是 x 的新值。
def percentError():
x = 1
#defining formula
error = str(100 * (measured - accepted) / (accepted))
#opening % Error.txt
errorTxt = open('% Error.txt', 'a')
#writing in file
errorTxt.write('Trial ' str(x) ' % error = ' error '%')
#new line
errorTxt.write('\n')
#close file
errorTxt.close()
#open file again
errorTxt = open('% Error.txt', 'r')
#read from and print what is read
trial = []
trialNum = []
for line in errorTxt:
trial.append(line.strip())
print(trial[-1])
for attribute in trial[-1]:
z = trial.split(' ')
trialNum.append(z)
x = trialNum[1]
#file close
errorTxt.close()
注釋上方有代碼(#defining 公式),其中包含測量和接受變數的用戶輸入,為了便于閱讀,我將其省略了。
這給了我錯誤 - AttributeError: 'list' has no attribute 'split'
有人知道如何解決我的問題嗎?目標是使 x 僅從檔案中的最高試驗編號增加 1。
uj5u.com熱心網友回復:
您可以使用該re模塊撰寫一個簡單的標記器。也許是這樣的:
import re
def simple_tokenize(text):
return re.sub(r"\W", " ", text).split()
然后,您可以將文本字串串列轉換為單詞串列,例如:
data_in = [
"To be, or not to be, that is the question:",
"Whether ’tis nobler in the mind to suffer",
"The slings and arrows of outrageous fortune,",
"Or to take arms against a sea of troubles,",
"And by opposing end them?"
]
data_out = [simple_tokenize(line) for line in data_in]
print(data_out)
給你:
[
['To', 'be', 'or', 'not', 'to', 'be', 'that', 'is', 'the', 'question'],
['Whether', 'tis', 'nobler', 'in', 'the', 'mind', 'to', 'suffer'],
['The', 'slings', 'and', 'arrows', 'of', 'outrageous', 'fortune'],
['Or', 'to', 'take', 'arms', 'against', 'a', 'sea', 'of', 'troubles'],
['And', 'by', 'opposing', 'end', 'them']
]
查看您的特定代碼和您對最終要做什么的描述,我認為您可以洗掉很多代碼,并且您正在做的一堆作業/拆分/決議是多余的。
如果你想:
- 計算用戶輸入給出的兩個值之間的百分比誤差。
- 將該值寫入字串中的檔案:'Trial x % error = y'
- 根據先前資料確定試驗的功能
你可以試試:
def percentError(measured, accepted):
error = 100 * (measured - accepted) / (accepted)
with open('percent_error.txt', 'a ') as error_file:
error_file.seek(0)
try:
last_line = error_file.readlines()[-1]
last_trial_number = int(last_line.split()[1])
except (ValueError, IndexError):
last_trial_number = 0
last_line = f"Trial {last_trial_number 1} % error = {error}%"
error_file.write(f"{last_line}\n")
print(last_line)
percentError(10,8)
percentError(10,9)
percentError(10,7)
user_measured = int(input("enter measured: ")) ## note this is brittle and will error if the user enters bad data
user_accepted = int(input("enter accepted: ")) ## note this is brittle and will error if the user enters bad data
percentError(user_measured, user_accepted)
應該向您展示:
Trial 1 % error = 25.0%
Trial 2 % error = 11.11111111111111%
Trial 3 % error = 42.857142857142854%
并根據您的用戶輸入進行第四次試用。
然后它將生成一個具有相同結果的檔案“percent_error.txt”
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407422.html
標籤:
下一篇:如何在顫動中將兩個串列相乘
