在python中操作文本文件

2024-10-01 13:44:55 发布

您现在位置:Python中文网/ 问答频道 /正文

带虚线和短划线的文本:

to validate my solution was
I need to take the bench test
of the elaborated algorithm
only after the table test that
the program was implemen-
ted this strategy spared
development time

代码:

def file_string():
    with open('speech.txt','r') as file:
        lines = file.read().split("\n")
     string = []
     for line in lines:
         line = line.replace('-\n','')
         string.append(line)
     return (' '.join(string))

print(file_string())

正确输出:

to validate my solution was I need to take the bench test of the elaborated algorithm only after the table test that the program was implemented this strategy spared development time

退出我的代码:

to validate my solution was I need to take the bench test of the elaborated algorithm only after the table test that the program was implemen- ted this strategy spared development time

文本是在文本编辑器中编写的。在

我需要这个帮助。在

applying the code sujerido the exit remained:

to validate my solution was I need to take the bench test of the elaborated algorithm only after the table test that the program was implemen ted this strategy spared development time

只有当我读到用文本编辑器编写的文件时,我需要用这些单词创建一个列表来进行比较。在


Tags: ofthetotestonlystringmyneed
2条回答

这条线

lines = file.read().split("\n")

'\n'从行中删除,因为它拆分了行。你分割的角色永远不会成为结果的一部分。在

所以这条线

^{pr2}$

找不到任何可以替代的东西。在

使用line = line.rstrip("-")代替,它将从right end of your string中删除{}(如果存在)。在

阅读/跟随How to debug small programs (#1)-可以获得一些关于如何调试自己的程序的提示。在

编辑:

  • 从分割线的' '-join()得到一个“”-您需要跟踪哪些行以-结束,并将其与下面的一行合并。简单地做两次替换就更容易了:

def file_string():
    with open('speech.txt','r') as file:
        lines = file.read()

    return lines.replace('-\n','').replace('\n', ' ') 

print(file_string())

为了得到你想要的结果。取消注释注释行并删除lines = """..."""。在

这可以(更新)吗?在

import re

def file_string():
    with open('speech.txt','r') as file:
        lines = file.read()
    lstr = re.sub(r'\-[\n]*',r'',lines)
    lstr = re.sub(r'[\n]+',r' ',lstr)
    return lstr

print(file_string())

相关问题 更多 >