将文件中以“ \”

时间:2018-11-09 00:33:19

标签: python

我真的是python的新手,由于某种原因,这使我感到困扰了一段时间,所以我想寻求帮助。

我正在研究一个python脚本,该脚本允许我读取文件,但是如果行末尾有'\',它将在其后加入行。

因此,如果这些行如下所示:

: Student 1 
: Student 2 \
Student 3

任何没有冒号的行,如果前一行有'\',我想将它们组合成这样:

: Student 2 Student 3

这是我尝试过的:

s = ""    
if line.endswith('\\'): 
   s.join(line) ## line being the line read from the file

任何在严格方向上的帮助都是很好的

3 个答案:

答案 0 :(得分:1)

s.join并没有您认为的那样。还要考虑到文件中的行具有换行符('\n'),因此.endswith('\\')不会因为这个原因而被捕获。

类似的东西(尽管方法有所不同)

output = ''
with open('/path/to/file.txt') as f:
    for line in f:
        if line.rstrip().endswith('\\'):
            next_line = next(f)
            line = line.rstrip()[:-1] + next_line
        output += line

在上面,我们使用line.rstrip()来读取任何结尾的空格(换行符),以便.endswith方法可以正确匹配。

如果一行以\结尾,我们将继续使用内置函数next将下一行从文件生成器中拉出。

最后,我们将行和下一行结合起来,注意再次删除空白(.rstrip())和\字符([:-1]表示直到最后一个字符的所有字符)然后将新行添加到输出中。

结果字符串像这样打印出来

: Student 1 
: Student 2 Student 3

关于s.join的注释...最好用split作为分隔符(或连接符)解释为s 相反。

>>> "foo.bar.baz".split('.')
['foo', 'bar', 'baz']
>>> "|".join(['foo', 'bar', 'baz'])
'foo|bar|baz'

答案 1 :(得分:0)

如果您可以读取完整文件而不将其分成几行,则可以使用正则表达式:

import re

text = """
: Student 1 
: Student 2 \
Student 3
""".strip()

print(re.sub(r'\\\s*\n[^:]', ' ', text))

: Student 1 
: Student 2 Student 3

正则表达式匹配\的出现,后跟换行和不是:的内容。

答案 2 :(得分:0)

如果以字符串列表开头,则可以使用var s = "foo\nbar\nbob"; console.log( s.replace(/\n/g, String.raw`\ `) // template literal contains one backslash, followed by one newline );regex来避免循环。

join

输出:

l = ['a\\', 'b','c']
s = '_'.join(l)
lx = re.split(r'(?<!\\)_', s) # use negative lookbehind to only split underscore with no `\` before it
[e.replace('\\_', '') for e in lx] # replace with '', ' ' if you need so.
相关问题