我有一个包含大文本文件输入的字符串变量。文本文件中的注释以“#”开头,以新行结束。
所以,我想要做的是从这个字符串生成另一个字符串,其中所有这些注释行以“#”开头并以换行符结尾。
所以,我认为我可以做一些我可以将字符串拆分为:
def transform_string(input):
output = ''
# Look for #
sub_strs = input.split('#')
for s in sub_strs:
# Look for newline
sub_sub_strs = s.split('\r\n')
for j in sub_sub_strs:
output += j
return output
然而,它看起来很难看,我想知道是否有一种更优雅的,pythonic方式来做到这一点。此外,这很容易出错。因为每个'#'将有一个相应的换行符,我想在第一次出现时进行拆分而不是拆分所有'\ r \ n',我认为。
答案 0 :(得分:2)
正则表达式可以起作用:
# Python 2.7
import re
def stripComment(text): return re.sub(r'#.*$', '', text)
print(stripComment("Hello there"))
# Hello there
print(stripComment("Hello #there"))
# Hello
这应该允许处理整行的注释,或者注释从中间某处开始的行(保留注释之前的内容)
答案 1 :(得分:2)
生成器可能是这里最恐怖的解决方案:
def clean_input(filename):
with open(filename, 'r') as f:
for line in f:
if not line.lstrip().startswith('#'):
yield line
for line in clean_input('somefile.txt'):
...
这允许您移动注释剥离或您需要的任何其他预处理,而不是文件的实际处理,您可以在其中迭代已清理的数据。
答案 2 :(得分:1)
如你所说,你正在阅读一个文本文件,你最好在阅读文件时这样做:
data = []
with open("input_file.txt") as f:
for line in f:
if not line.startswith("#"):
data.append(line)
data = "".join(data)
这最后的连接步骤不是最佳的 - 如果可以的话,你应该单独处理每一行,这样你就不需要整个文件在内存中了。
答案 3 :(得分:0)
您可以使用列表推导来过滤行:
>>> txt = """some lines
... #some commented
... some not
... #othe comment
... other line"""
>>> '\n'.join(line for line in txt.splitlines() if not line.startswith('#'))
'some lines\nsome not\nother line'