如何从文本文件中读取值,将其存储在数组中,然后循环它?

时间:2017-07-01 00:59:38

标签: python for-loop if-statement readfile

根据包维度:HeightLengthWidthWeight,我创建了3个包类别:Letter,{ {1}}和Parcel-Small。这是python中的代码:

Parcel-Large

正如所见,这些维度值是硬编码的。我想从文本文件中获取输入(def category(row): if(row['Height'] <=0.98 and row['Length'] <= 9.84 and row['Width'] <= 13.89 and row['WEIGHT'] <= 1.65): val = 'Letter' elif(row['Height'] <=6.29 and row['Length'] <= 13.77 and row['Width'] <= 17.71 and row['WEIGHT'] <= 4.4): val = 'Parcel-Small' elif(row['Height'] <=6.29 and row['Length'] <= 13.77 and row['Width'] <= 17.71 and row['WEIGHT'] <= 4.4): val = 'Parcel-Large' return val Package CategoryHeightLengthWidth),格式如下:< / p>

Weight

它应该读取用户指定的多个类别,代码应该是这样的:

Package Category : Height, Length, Width, Weight
Small:2,3,4,10
Medium:3,5,7,15
Large:5,7,9,20

有人可以为上面给出的伪代码提供实际代码吗?

4 个答案:

答案 0 :(得分:0)

使用小循环,您可以将该文件解析为list dicts之类的... {/ p>

代码:

package_types = []
with open('file1', 'rU') as f:
    header = next(f)
    columns = [x.strip() for x in header.split(':')[1].split(',')]
    for line in f:
        name, data = line.split(':')
        package_types.append(dict(zip(columns,
            [float(x) for x in data.split(',')])))
        package_types[-1]['type'] = name

for package_type in package_types:
    print(package_type)

    # if package_type['Height'] <= Height and not ...

结果:

{'Width': 4.0, 'Length': 3.0, 'type': 'Small', 'Weight': 10.0, 'Height': 2.0}
{'Width': 7.0, 'Length': 5.0, 'type': 'Medium', 'Weight': 15.0, 'Height': 3.0}
{'Width': 9.0, 'Length': 7.0, 'type': 'Large', 'Weight': 20.0, 'Height': 5.0}

答案 1 :(得分:0)

这是我的解决方案:

配置文件示例( categories.dt ):

Letter : 0.98, 9.84, 13.89, 1.65
Parcel-Small : 3.63, 11.80, 15.80, 3.02
Parcel-Large : 6.29, 13.77, 17.71, 4.4

解析文件的函数:

def parse_file(f):
    categories = [] # Create empty list
    for line in f:
        line = line.strip() # Remove leading and trailing spaces
        name, tail = line.split(':') # Separate the name of the category from its specifications
        height, length, width, weight = tail.split(',') # Separate each specification
        # Convert each specification to a number (float) and put them all in a dictionary
        specs = {'height': float(height),
                 'length': float(length),
                 'width': float(width),
                 'weight': float(weight)}
        categories.append((name, specs)) # Append the name and the specifications to a list
    return categories

打开文件并构建列表:

with open('categories.txt', 'r') as f:
    categories = parse_file(f)

将测量分类为类别的功能:

def category(height, length, width, weight):
    for name, specs in categories:
        if height <= specs['height'] and length <= specs['length'] and width <= specs['width'] and weight <= specs['weight']:
            return name

用法示例:

print category(3, 11, 15, 3)

输出:

Parcel-Small

答案 2 :(得分:0)

您为包类别定义文件选择的格式有点难以解析它几乎一个csv格式文件,但不完全(它使用多个分隔符和放置其中的空格不一致)。也就是说,这里有处理它的东西,并按照你想要的处理进行处理:

import csv
from collections import namedtuple

def as_csv(filename):
    """ Make configuration file look like it's in csv format. """
    with open(filename, newline='') as file:  # in Python 2 change newline='' to mode='rb'
        next(file)  # ignore first row
        for line in file:
            yield line.replace(':', ',')

PackageSpec = namedtuple('PackageSpec', 'category, height, length, width, weight')
DATA_TYPES = str, float, float, float, float

package_specs = [PackageSpec(*(datatype(val) for (datatype, val) in zip(DATA_TYPES, data)))
                    for data in csv.reader(as_csv('package_categories.txt'))]

def category(row):
    for spec in package_specs:
        if(row['Height'] <= spec.height and row['Length'] <= spec.length
           and row['Width'] <= spec.width and row['Weight'] <= spec.weight):
            return spec.category

sample_row = dict(Height=3, Length=5, Width=7, Weight=15)
print(category(sample_row))  # -> Medium

答案 3 :(得分:-1)

好的,我确定发布一个不完整的答案可能是不好的形式,但这确实是找出他所寻找内容的唯一方法。

我们仍然需要知道您使用哪种文件格式作为类别列表和包列表。

# This is the list of actual packages you're trying to categorize
# Codes not ready yet, we still need to open whatever kind of file
# You plan to use

list_of_real_packages = "CSV File?"

# This assumes categories are ordered smallest to largest
# We need to parse a real file, I'm just showing what it might look
# like based on your example
sample_categories_spreadsheet = [
    {
        'name': 'letter',
        'height': 0.98,
        'length': 9.84,
        'width': 13.89,
        'weight': 1.65
    },
    {
        'name': 'parcel-small',
        'height': 6.29,
        'length': 13.77,
        'width': 17.71,
        'weight': 4.4
    },
    {
        'name': 'parcel-large',
        'height': 12.00,
        'length': 20.00,
        'width': 25.00,
        'weight': 10
    },

]


def get_category_per_package_in_list(list_or_file_with_real_package_dimensions):
    package_number = 1
    package_list_with_categories = []

    # Check each package to see if it meets current categories criteria
    # Smallest to largest, because a small package will meet multiple criteria
    for package in list_or_file_with_real_package_dimensions:
        current_package = {}
        current_package['package_id'] = package_number,
        current_package['height'] = package['height'],
        current_package['length'] = package['length'],
        current_package['width'] = package['width'],
        current_package['weight'] = package['weight'],
        for catagory in sample_categories_spreadsheet:
            if package['height'] <= category['height']:
                if package['length'] <= category['length']:
                    if package['width'] <= category['width']:
                        if package['weight'] <= category['weight']:
                            current_package['category'] = category['name']

    # It's possible there is a very long skinny package that doesn't meet
    # any criteria, so we'll give it a category so we can look into it
    # after we sort the more standard packages
    else:
        current_package['category'] = 'Outside range of given categories'

    package_list_with_categories.append(new_package)
    return package_list_with_categories

list_of_packages = get_category_per_package_in_list()