我搜索过字符串,列表,附加等等但似乎无法处理这个问题。
我根据在应用程序中完成的选择从android创建了一些文件。 输出如下所示,位于文本文件中:
House 1,bwfront3,colorfront2,bwtilt3,colortilt3 House 2,bwfront6,colorfront6,bwtilt6,colortilt6 House 3,bwfront5,colorfront5,bwtilt5,colortilt5 House 4,bwfront4,colorfront4,bwtilt4,colortilt4 House 5,bwfront2,colorfront2,bwtilt2,colortilt2
命名的原因:
练习是将不同的照片映射到'房子'。
我现在希望加载文本文件并计算每个不同的'bwfront'被选中的数量等等。为了澄清,用户每个'house'选择四次。
有意义吗?
答案 0 :(得分:1)
解析这样一个文件以计算不同bwfronts的可能方法:
import csv
from collections import Counter
def count_bwfronts():
"""Counts occurrences of different bwfronts in
yourfile.txt. Returns a Counter object which
maps different bwfront values to a number of their
occurances in the file."""
reader = csv.reader(open('yourfile.txt', 'rb'), delimiter=",")
counter = Counter()
counter.update(row[1] for row in reader)
return counter
if __name__ == "__main__":
print count_bwfronts()
正如您可能已经猜到的那样,从阅读器中获取的每一行只是一个字符串列表,以前在输入文件中用逗号分隔。为了进行更复杂的计算,您可能希望将生成器表达式重写为循环。
答案 1 :(得分:0)
# First, create a dictionary for each column, that maps each
# value (eg colorfront2) to a list of house names.
results = [{}, {}, {}, {}]
for filename in os.listdir('/wherever'):
s = open(os.path.join('/wherever', filename), 'rb').read()
for line in s.split('\n'):
if not line.strip(): continue # skip blank lines
house, values = line.split(',', 1)
values = values.split(',')
assert len(values) == len(results) # sanity check
for value, result in zip(values, results):
if value not in result:
result[value] = []
result[value].append(house)
# Then, do something with it -- e.g., show them in order
for i, result in enumerate(results):
print 'COLUMN %d' % i
def sortkey(pair): return len(pair[1]) # number of houses
for (val, houses) in sorted(result.items(), key=sortkey, reverse=True):
print ' %20s occurs for %d houses' % (val, len(houses))
答案 2 :(得分:0)
这将遍历文件并提取一行的每一部分并将其存储在一个5元组的列表中,从那里你可以用你的房子/颜色等做任何你需要的事情。这只是一个例子,因为很难准确确定脚本需要什么,但这应该有助于您入门:
houses = open("houses.txt", "r")
house_list = []
for line in houses:
# This assumes each line will always have 5 items separated by commas.
house, bwfront, colorfront, bwtilt, colortilt = line.split(",")
# This strips off the initial word ("bwfront") and just gives you the number
house_num = house[6:]
bwfront_num = bwfront[7:]
colorfront_num = colorfront[10:]
bwtilt_num = bwtilt[6:]
colortilt_num = colortilt[9:]
house_list.append((house_num, bwfront_num, colorfront_num, bwtilt_num, colortilt_num))
print house_list
结果:
[('1', '3', '2', '3', '3'), ('2', '6', '6', '6', '6'), ('3', '5', '5', '5', '5'), ('4', '4', '4', '4', '4'), ('5', '2', '2', '2', '2')]
从那里,您可以执行[h[1] for h in house_list]
之类的操作来获取每个房屋的所有bwfront
个数字等等:
['3', '6', '5', '4', '2']