你可以使用Python的`readlines`函数来按特定模式格式化文件中的行。

huangapple go评论59阅读模式
英文:

How can I use Python's readlines function to format lines from a file in a specific pattern?

问题

我已经修改了您的代码以获得预期的结果:

import re

with open("test.txt", "r") as data_file:
    lines = data_file.readlines()

result = ""
for line in lines:
    cleaned_line = re.sub(r"[^X]+", "-", line.strip())
    result += cleaned_line + "\n"

print(result.strip())

这将输出以下结果:

XX-X
XX-X-X

请使用这个修改后的代码来获得您期望的输出。

英文:

The data I have in the test.txt file looks like this:

XXTYSVASOOXOSJAY
CGTVHIXXHIAICXWHAYX

and I'm trying to achieve a pattern like this:

XX-X
XX-X-X

This is what I have so far:

import re

data = open("test.txt", "r")
lines = data.readlines()

result = re.sub(r"[^X]+", r"-", str(lines)).strip("-")
if "X" in result:
  print(result)
else:
  print("No X found")

This is the result I get, it's a single line: XX-X-XX-X-X.

How can I do this correctly to get the expected result?

答案1

得分: 1

要按特定模式格式化文件中的行,您可以迭代文件中的每一行,并对每一行分别应用正则表达式替换。例如

import re

with open("test.txt", "r") as f:
    for line in f:
        result = re.sub("[^X]+", "-", line).strip("-")
        print(result if "X" in result else "未找到 X")
英文:

To format lines from a file with a specific pattern, you can iterate over each line in the file and apply regular expression substitution to each line apart. For example

import re

with open("test.txt", "r") as f:
    for line in f:
        result = re.sub(r"[^X]+", r"-", line).strip("-")
        print(result if "X" in result else "No X found")

huangapple
  • 本文由 发表于 2023年5月30日 03:03:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76359786.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定