英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论