快速问题:如何编写代码清洁器?我可以不重复自己而一起写'with'和'if'陈述式吗? -感谢所有提示。
with open('Requirements_good.txt') as myfile:
Sentence = myfile.readlines()
Sentence = list(map(lambda s: s.strip(), Sentence))
#get data
with open('Badwords_conjunctive.txt') as myfile:
conjunctive_list = myfile.readlines()
conjunctive_list = list(map(lambda s: s.strip(), conjunctive_list))
with open('Badwords_unprecise.txt') as myfile:
unprecise_list = myfile.readlines()
unprecise_list = list(map(lambda s: s.strip(), unprecise_list))
with open('Badwords_other.txt') as myfile:
other_list = myfile.readlines()
other_list = list(map(lambda s: s.strip(), other_list))
if any(word in Sentence for word in unprecise_list):
print('Your words of choice have unprecise definitions')
if any(word in Sentence for word in conjunctive_list):
print('Conjunctive should rather be avoided')
if any(word in Sentence for word in other_list):
print('You wrote a word that should rather be avoided')
答案 0 :(得分:2)
是的,可以。
with
和if
可以像这样一起使用:
with open('Badwords_unprecise.txt') as myfile:
unprecise_list = myfile.readlines()
unprecise_list = list(map(lambda s: s.strip(), unprecise_list))
if any(word in Sentence for word in unprecise_list):
print('Your words of choice have unprecise definitions')
这可以减少一行:
with open('Badwords_unprecise.txt') as myfile: if any(word in Sengence for word in myfile.readlines())
但是,根据PEP8,建议不要写太长的行。 可读性是Python语言的主要功能之一。 最好将长行分隔为较短的行。
答案 1 :(得分:1)
def fn(file_name):
data = []
with open(file_name) as myfile:
data = list(map(lambda s: s.strip(), myfile.readlines()))
return data
Sentence = fn("Requirements_good.txt")
conjunctive_list = fn("Badwords_conjunctive.txt")
...
答案 2 :(得分:1)
这可能属于“代码审查”。但是,我确实想共享重构版本,我对当前的答案不满意。
with open('Requirements_good.txt') as curr_file:
sentence = [line.strip() for line in curr_file]
with open('Badwords_conjunctive.txt') as curr_file:
conjunctive_list = [line.strip() for line in curr_file]
with open('Badwords_unprecise.txt') as curr_file:
unprecise_list = [line.strip() for line in curr_file]
with open('Badwords_other.txt') as curr_file:
other_list = [line.strip() for line in curr_file]
if any(word in sentence for word in unprecise_list):
print('Your words of choice have unprecise definitions')
if any(word in sentence for word in conjunctive_list):
print('Conjunctive should rather be avoided')
if any(word in sentence for word in other_list):
print('You wrote a word that should rather be avoided')
我认为这对程序的其余部分做出了尽可能少的假设。