You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.sub calls, 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 urlencode directly into re.sub instead 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 map to decode and strip each line once, avoiding duplicate decoding in the if check. Wrapping urlopen in a with statement 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), and urlencode works 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:09:08