我是Python的新手,我試圖從URL(每行一個URL)中刪除註釋和註釋行。我爲了使用自定義ArgumentParser(argparse)和重寫convert_arg_line_to_args: -Python如何從文件中跳過註釋行ArgumentParser.convert_arg_line_to_args
- 地帶在線的端尾隨註釋例如'http://example.com# 評論'
- 帶狀線是空的或整條線例如「# 此文件包含的URL,每行一個」
我能夠成功地刪除尾隨註釋(1),但似乎無法刪除空行或註釋行(2)。整行註釋和空行保留在我的文件列表中。
class CustomArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
super(CustomArgumentParser, self).__init__(*args, **kwargs)
def convert_arg_line_to_args(self, line):
'''Strip out comments from start points file'''
if re.match('^#.*', line, 0) or re.match('^\s+$', line, 0):
yield
arg = re.sub('\s+#.*$', '', line)
yield arg
有沒有辦法刪除空行和註釋行?
實施例的輸入文件是:
# Start points for the spider
#
http://www.website1.com/News.html?typeid=8 # All news
http://www.website1.com/News.html?typeid=5 # Business
http://www.website2.com/News.html?category=All%20Category%20News
http://www.website2.com/News.html?category=Category2
原始代碼給出ARGS返回從parse_args()
爲:
DEBUG:root:Args are: Namespace(URLs=['', '# Start points for the spider ', '', '#', 'http://www.website1.com/News.html?typeid=8', 'http://www.website1.com/News.html?typeid=5', 'http://www.website1.com/News.html?typeid=9', 'http://www.website1.com/News.html?typeid=10', 'http://www.website1.com/KeyInterviews.html', '', '', 'http://www.website2.com/News.html?category=All%20Category%20News', 'http://www.website2.com/News.html?category=Category2'], cacheDir='/tmp', debug_level=' 1', firstNPages=None, outputDir=None, storyType='news')
更改以產生空列表給出:
DEBUG:root:Args are: Namespace(URLs=[[], '# Start points for the spider ', [], '#', 'http://www.website1.com/News.html?typeid=8', 'http://www.website1.com/News.html?typeid=5', [], '', 'http://www.website2.com/News.html?category=All%20Category%20News', 'http://www.website2.com/News.html?category=Category2'], cacheDir='/tmp', debug_level=' 1', firstNPages=None, outputDir=None, storyType='news')
我想參數看起來像:
DEBUG:root:Args are: Namespace(URLs=['http://www.website1.com/News.html?typeid=8', 'http://www.website1.com/News.html?typeid=5', 'http://www.website2.com/News.html?category=All%20Category%20News', 'http://www.website2.com/News.html?category=Category2'], cacheDir='/tmp', debug_level=' 1', firstNPages=None, outputDir=None, storyType='news')
也許不可能以這種方式從輸入文件中刪除行。
你爲什麼使用'argparse'解析一個*文件?*這是命令行參數!你會如何使用它?你能否給一個[mcve]更清楚地解釋這個問題? – jonrsharpe
以「@」開頭的參數被解釋爲包含更多參數的文件的名稱,默認情況下每行一個。 'convert_arg_line_to_args'可以讓你使用更復雜的文件格式。 – chepner
不要**產生一個空列表,但**返回**一個。 – memoselyk