从包含字符串和整数的文本文件中获取数据(Python)
问题描述:
我有一个关于从文本文件中获取数据的问题,该文本文件包括简单地添加/平均来自文件内不同行的数据。从包含字符串和整数的文本文件中获取数据(Python)
pos1 250 184 196
pos2 167 321 459
我需要添加整数250
和167
并产生一个总。我很乐于在同一行上添加整数,并获得总数,平均值等(总计250 + 184 + 196)。
def calculateTotal():
for i in range(1):
userChoice2 = int(input(
"1. Total feedback that is good.\n2. Total feedback that is fair.\n3."
" Total feedback that is poor.\n......:")) -1
if userChoice2 > 3:
time.sleep(0.5)
print(
"\n******************************\nInvalid choice, please choose again.\n******************************\n")
time.sleep(0.5)
calculateTotal()
else:
goodfeedback2 =
fairFeedback2 =
poorFeedback2 =
print("Total good feedback is: ", goodfeedback2)
time.sleep(1)
allDepartments = readData("data.txt")
我刚刚就如何解决它的一些建议。
total = allDepartments[userChoice][1] + allDepartments[userChoice][2] + allDepartments[userChoice][3]
avg = (allDepartments[userChoice][1] * 3 + allDepartments[userChoice][2] * 2 + allDepartments[userChoice][
3])/total
time.sleep(1)
print('\nThe average is: ', format(avg, '.2f'), ' and the total number of votes for that department is:',
total, '\n******************************\n\n.....LOADING MENU.....\n')
答
我会考虑使用astropy,特别是ascii模块,它允许您将文本文件转换为numpy array。
from astropy.io import ascii
with open("data.csv", "r+") as f:
data = ascii.read(f, delimiter=' ')
不要忘记皮条客你的ascii.read()参数,以防万一默认行为不适合你。
将数据存入数组后,您可以使用numpy的所有功能来计算列和行的平均值,平均值,以及更易读的一行数据。
答
with open('data.txt') as f:
net_good = 0
net_fair = 0
net_poor = 0
for line in f:
pos, n_good, n_fair, n_poor = line.split() # Assumes no missing values
net_good += n_good
net_fair += n_fair
net_poor += n_poor
total = net_good*3 + net_fair*2 + net_poor
# Do user input stuff
答
好像你之后,两件事情。如何读取文件以及如何拆分字符串。
已经有上,这样介绍了如何读取文件太多的问题,但官方文档是好的:https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
然后你想,当你使用STR读它拆分数据的每一行。拆分(splitter)命令:'12 34 56'.split(' ')
会给你一个清单:['12', '34', '56']
。你可以通过做sum(int(i) for i in list)
得到这个清单的总和。
如果你想从文本文件中得到一个numpy数组,你可以简单地使用'numpy.loadtxt'。不需要额外的模块。 – Mel
@tmoreau好点!如果文本文件非常简单并且没有缺失单元格,[genfromtxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html#numpy.genfromtxt)以获得更大的灵活性。谢谢! – joris255