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

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

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

问题

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

  1. import re
  2. with open("test.txt", "r") as data_file:
  3. lines = data_file.readlines()
  4. result = ""
  5. for line in lines:
  6. cleaned_line = re.sub(r"[^X]+", "-", line.strip())
  7. result += cleaned_line + "\n"
  8. print(result.strip())

这将输出以下结果:

  1. XX-X
  2. XX-X-X

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

英文:

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

  1. XXTYSVASOOXOSJAY
  2. CGTVHIXXHIAICXWHAYX

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

  1. XX-X
  2. XX-X-X

This is what I have so far:

  1. import re
  2. data = open("test.txt", "r")
  3. lines = data.readlines()
  4. result = re.sub(r"[^X]+", r"-", str(lines)).strip("-")
  5. if "X" in result:
  6. print(result)
  7. else:
  8. 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

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

  1. import re
  2. with open("test.txt", "r") as f:
  3. for line in f:
  4. result = re.sub("[^X]+", "-", line).strip("-")
  5. 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

  1. import re
  2. with open("test.txt", "r") as f:
  3. for line in f:
  4. result = re.sub(r"[^X]+", r"-", line).strip("-")
  5. 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:

确定