减少python上if语句的数量
我要分析一个txt文件,它看起来像:减少python上if语句的数量,python,python-3.x,parsing,dictionary,if-statement,Python,Python 3.x,Parsing,Dictionary,If Statement,我要分析一个txt文件,它看起来像: --- What kind of submission is this? --- Sold Property --- State? --- Los Angeles ... 并且需要在变量中的--标记后存储值。它适用于所有的if语句,但我想知道是否有可能将大量的if重构成某种结构(例如字典),然后轻松地将其写入输出文件 这是我做的东西: """Open a file to read""" for line in res:
--- What kind of submission is this? ---
Sold Property
--- State? ---
Los Angeles
...
并且需要在变量中的--
标记后存储值。它适用于所有的if语句,但我想知道是否有可能将大量的if重构成某种结构(例如字典),然后轻松地将其写入输出文件
这是我做的东西:
"""Open a file to read"""
for line in res:
if "Instagram Usernames" in line:
usernames = next(res)
if "Date" in line:
date = next(res)
if "Address" in line:
address = next(res)
if "Neighborhood" in line:
market = next(res)
if "State" in line:
city = next(res)
if "Asset" in line:
as_type = next(res)
if "Sale Price" in line:
price = next(res)
if "," in price:
price = price.replace(',', '')
if "$" in price:
price = price.replace('$', '')
if "Square" in line:
sf = next(res)
if "," in sf:
sf = sf.replace(',', '')
if "$" in sf:
sf = sf.replace('$', '')
if "Buyer" in line:
buyer = next(res)
if "Seller" in line:
seller = next(res)
if "Broker" in line:
brokers = next(res)
if "Notes" in line:
notes = next(res)
"""Write to output file"""
fin.write("IMAGE: @" + usernames)
fin.write("DATE: " + date)
fin.write("ADDRESS: " + address)
fin.write("MARKET: " + market)
fin.write("CITY: " + city)
if as_type == "Multi Family" or "Multi Family\n":
fin.write("ASSET TYPE: Multifamily\n")
else:
fin.write("ASSET TYPE: " + as_type)
fin.write("PRICE: $" + price)
if sf in bad_symb:
fin.write("SF: N/A\n")
fin.write("PPSF: N/A\n")
else:
fin.write("SF: " + sf)
fin.write("PPSF: $" + "{0:.2f}\n".format(float(price) / float(sf)))
fin.write("BUYER: " + buyer)
fin.write("SELLER: " + seller)
fin.write("BROKERS: " + brokers + "\n")
if notes != "\n":
fin.write("NOTES: " + notes + "\n")
fin.write(footer_sale(market, buyer, seller))
任何帮助都将不胜感激,提前感谢 可以使用字典,破折号之间的所有内容都是键,下一行是对应的值 由于不使用循环,我们首先将文件内容拆分为行:
res = res.split("\n")
下一行生成字典res[::2]
选择res
中的每一秒项,从第一项开始(所有行都有--
),res[1::2]
每一秒项,从第二项开始(所有行都有信息)
现在,我们选择带有--
的行作为字典中每个条目的键,选择信息行作为值:key:value
;由于您可能不希望包含破折号,因此我们使用.rstrip(“-”
)从开头和结尾剥离破折号和空格:
现在,您可以轻松地索引
x
以获取所需信息,这也将简化对输出文件的写入。使用定义的lambda函数从所有行字符串列表中查找下一行字符串
search_func = lambda search_str : [line_list[line_list.index(line)+1] for line in line_list[:-1] if search_str in line]
将变量作为键获取,并将相应的特定搜索字符串作为另一个字典中的值获取:
all_vars_search_dict = {'usernames' : "Instagram Usernames" , 'date' : "Date", 'address' : "Address", 'market' : "Neightbourhood", 'city' : "State",...}
现在,创建另一个调用previous函数的字典,以获取所需的搜索值:
all_vals = {k: search_func(all_vars_search_dict[k]) for k in all_vars_search_dict}
在写入输出文件时,只需迭代该字典即可
注意:这个过程不能用于搜索行中的关键字
“Square”
和“Sale Price”
。当我有一系列这样的项目时,我喜欢设置一个小的数据结构,指定我要查找的内容,以及如果我找到了它应该放在哪里
def strip_currency(s):
"""Function to strip currency and commas from a real number string"""
return s.replace('$', '').replace(',', '')
# mapping of data labels to attribute/key names
label_attr_map = (
('Instagram Usernames', 'usernames'),
('Date', 'date'),
('Address', 'address'),
('Neighborhood', 'market'),
('State', 'city'), # <-- copy-paste bug?
('Asset', 'as_type'),
('Sale Price', 'price', strip_currency),
('Square', 'sf', strip_currency),
('Buyer', 'buyer'),
('Seller', 'seller'),
('Broker', 'broker'),
('Notes', 'notes'),
)
# populate data dict with values from file, as defined in the label_attr_map
data = {}
for line in file:
# find any matching label, or just go on to the next line
match_spec = next((spec for spec in label_attr_map if spec[0] in line), None)
if match_spec is None:
continue
# found a label, now extract the next line, and transform it if necessary
key = match_spec[1]
data[key] = next(file)
if len(match_spec) > 2:
transform_fn = match_spec[2]
data[key] = transform_fn(data[key])
def strip\u货币:
“”“从实数字符串中去除货币和逗号的函数”“”
返回s.replace(“$”,“”)。replace(“,”,“”)
#数据标签到属性/键名称的映射
标签属性映射=(
(‘Instagram用户名’、‘用户名’),
(“日期”、“日期”),
(‘地址’、‘地址’),
("街坊","街市"),,
(“州”、“市”),#2:
转换\u fn=匹配\u规范[2]
数据[键]=转换\u fn(数据[键])
现在,标签到属性的映射更容易验证,而“if”的级联只是一个next
表达式
要写入输出,只需访问
数据
目录中的不同项。函数映射如何?您需要将函数引用存储在目录中,作为fmap={'Square':Square,)现在您需要从函数中获取它,并调用给定的函数(如果找不到该函数),然后只要找到开始使用('--')的行,就可以忽略
您可以将其内容存储为dict中的键,下一行作为值。这将替换所有if
语句。您是老板!这是我在项目中尝试实现的,非常感谢:)
def strip_currency(s):
"""Function to strip currency and commas from a real number string"""
return s.replace('$', '').replace(',', '')
# mapping of data labels to attribute/key names
label_attr_map = (
('Instagram Usernames', 'usernames'),
('Date', 'date'),
('Address', 'address'),
('Neighborhood', 'market'),
('State', 'city'), # <-- copy-paste bug?
('Asset', 'as_type'),
('Sale Price', 'price', strip_currency),
('Square', 'sf', strip_currency),
('Buyer', 'buyer'),
('Seller', 'seller'),
('Broker', 'broker'),
('Notes', 'notes'),
)
# populate data dict with values from file, as defined in the label_attr_map
data = {}
for line in file:
# find any matching label, or just go on to the next line
match_spec = next((spec for spec in label_attr_map if spec[0] in line), None)
if match_spec is None:
continue
# found a label, now extract the next line, and transform it if necessary
key = match_spec[1]
data[key] = next(file)
if len(match_spec) > 2:
transform_fn = match_spec[2]
data[key] = transform_fn(data[key])