Python3:如何精简移除URL特定字符的字典转URL代码?
Optimized Version of Your Code
Here's a more concise and readable take on your code, with key optimizations broken down below:
import urllib.parse import urllib.request import re # User input start = '19851123' end = '19851124' stns = [('235','240')] var = ['TEMP'] # Fixed: ('TEMP') is just a string—parentheses don't create a tuple here # Generate and clean query string in one chained step q = re.sub( r"[\(\)',]|\+", lambda match: ':' if match.group() == '+' else '', urllib.parse.urlencode( {'start': start, 'end': end, 'vars': var, 'stns': stns}, doseq=True, safe="()'," ) ) # Build URL with modern f-string url = f'http://projects.knmi.nl/klimatologie/daggegeven/getdata_dag.cgi?{q}' # Fetch and print non-header lines efficiently with urllib.request.urlopen(url) as fhand: for line in map(lambda l: l.decode().strip(), fhand): if not line.startswith('#'): print(line)
Key Optimizations:
- Combined Regex Cleanup: Instead of two separate
re.subcalls, we use a single regex pattern to target both the safe characters we want to remove (()',) and the+we want to replace with:. A lambda function handles the conditional replacement, cutting down on redundant processing. - Chained Query Generation: We pass the output of
urlencodedirectly intore.subinstead of using an intermediate variable, making the code tighter without sacrificing readability. - Modern String Formatting: Replaced the outdated
%formatting with an f-string for URL construction—this is more intuitive and aligned with current Python best practices. - Efficient Line Processing: Used
mapto decode and strip each line once, avoiding duplicate decoding in theifcheck. Wrappingurlopenin awithstatement also ensures proper resource cleanup (a good habit even if the connection auto-closes). - Simplified Input List: Changed
[('TEMP')]to['TEMP']since the parentheses don’t create a tuple here (you’d need('TEMP',)for that), andurlencodeworks identically with a list of strings.
Optional Extra Simplification:
If you’re working with small datasets and want to shorten the line-printing step further, you can use a generator expression with '\n'.join (note this loads all lines into memory at once):
with urllib.request.urlopen(url) as fhand: print('\n'.join(line.decode().strip() for line in fhand if not line.decode().startswith('#')))
内容的提问来源于stack exchange,提问作者Mark W
相关产品推荐
相关产品推荐

