简体   繁体   English

无法弄清楚在我的代码中放置“ \\ n”的位置,以便正则表达式逐行打印。

[英]Can not figure out where to put the '\n' in my code in order for regex to print line by line.

So I have been at this for a while now trying to figure out where to put the '\\n' in order for the output being set into a text document to be placed line by line. 因此,我已经花了一段时间了,试图弄清楚在何处放置“ \\ n”,以便将输出设置到文本文档中以逐行放置。 It is grouping the output into one big mess. 它将输出分组为一团糟。 I wanted for each line that matches my regex, to be saved on a seperate line. 我希望将与我的正则表达式匹配的每一行保存在单独的行中。

Code: 码:

import re


dns = []
with open('ns.txt', 'r') as file:
    lines = file.read().splitlines()
    for line in lines:
        if re.search(r'^(add lb vserver )(\S+) (\S+) (\S+)(.+)$', "line"):
            dns.append(line)
            print(dns)
    with open('dnsout.txt', 'w') as f:
        f.writelines(lines)

dns.append(line)必须是dns.append(line+"\\n")

updated (sorry for typo's) 更新 (对错打错了)

Since you're reading in all the lines into an array anyway. 因为无论如何您都将所有行读入数组。
Just read the entire file into a string. 只需将整个文件读入字符串即可。

Then clean it up with a find (?m)$(?:\\s*\\r?\\n)+ replace \\r\\n 然后使用查找(?m)$(?:\\s*\\r?\\n)+替换\\r\\n清理

Use whatever CRLF translation your system uses. 使用系统使用的任何CRLF转换。
This just removes all extra linebreaks. 这只会删除所有多余的换行符。

If you want to make it with an extra line separation, make the replacement \\r\\n\\r\\n . 如果要使用额外的行分隔符,请替换\\r\\n\\r\\n

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 新行的正则表达式无法弄清楚 - Regex for New Line Can't Figure out 如何一次从列表中打印出n(3)个项目,然后将它们显示在一行上。 Python 3 - How to print out n (3) items from a list at a time and then display them on one line. Python 3 我的代码中第 7 行的语法有什么问题? 它说我的打印语句有无效的语法,我无法弄清楚? - What is wrong with the syntax with line 7 in my code? It says my print statement has invalid syntax and I can't figure it out? RegEx 忽略注释行。 - RegEx Ignore a commented line. Python可以逐行打印一行(或顺序)的行吗? - Can Python print out the line by line flow (or order) of a run? 条件在同一行。 问题是它不打印下一行 - Condition on the same line. The problem is that it doesn't print the next line 我使用 python 创建了一个排行榜,但我的代码打印在一行中。 我希望它像排行榜格式一样单独打印每个元素 - I have created a leaderboard using python but my code prints in a single line. I want it to print each element separately like in a leaderboard format 如何在起始词到 '\\n' 新行之间拉词。 有没有办法在python中提取单词时放置“或”条件? - How to pull words between starting word till '\n' new line. and is there any way to put 'OR' condition while extracting words in python? Python 逐行比较 2 个文件。 如果文件 1 的行不在文件 2 的行中,则打印 - Python compare 2 files line by line. if line from file 1 is not in line from file 2, then print show_letters function 应该在单独的行上打印出单词的每个字母。 填空以实现这一目标 - The show_letters function should print out each letter of a word on a separate line. Fill in the blanks to make that happen
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM