Python 拆分时读取文件中的字符串()

Python 拆分时读取文件中的字符串(),python,file,python-3.x,split,Python,File,Python 3.x,Split,名为sketch1.txt的文件的内容 Man: Is this the right room for an argument? Other Man: I've told you once. Man: No you haven't! Other Man: Yes I have. Man: When? Other Man: Just now. Man: No you didn't! 代码: try: def read_file( ): data = open('C:

名为sketch1.txt的文件的内容

Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
代码:

try:
     def read_file( ):
          data = open('C:\\Users\\Adam\\Documents\\eBook\\PythonData\\sketch1.txt', 'r')
     print ("---- read all---")
     for read_lines in data:
          try:
               if read_lines.find(':') != -1:
                    (role, line_said) = read_lines.split(":", 1)
                    print(role +' says ' +line_said)
               else:
                    print(read_lines)
          except:
               pass

except:
     print("data file is missing")
结果: 工作过一次,但不是每次我跑步

---- read all---
Man says  Is this the right room for an argument?

Other Man says  I've told you once.

Man says  No you haven't!

Other Man says  Yes I have.
错误: 在大多数情况下,我最终只收到一份打印的对账单

  ---- read all---

您的示例中似乎缺少一些代码。例如,我不明白为什么您可以在没有在For循环的范围内定义数据的情况下循环数据(它只在read_file函数中定义,而read_file函数从未调用)。此外,代码不必要地复杂,因此,除非有任何特定的方法使用split,否则我将按如下方式执行:

with open('C:\\Users\\Adam\\Documents\\eBook\\PythonData\\sketch1.txt', 'r') as f:
    for line in f:
        print line.replace(':', ' says', 1)

这也将在您读完文件后关闭该文件(由于with语句)。

您是否调用过
read\u file
?!你只是想用says替换
吗?1)你的意思相当错误。。。现在您的
read\u文件()
只有一行;2) 阅读
str.partition()
3)阅读后关闭文件-最好使用
打开(文件名)作为f:…
construction…不在您发布的代码中。文件的工作原理类似于从磁带读取-到达末尾后必须倒带(
seek(0)
)。我建议您重新构造代码-除其他外,
try
块中的代码太多,您正在使用。作为补充说明,我建议将其用于文件名,即
r'C:\Users\Adam\Documents\eBook\pythonda\sketch1.txt'
。谢谢,我喜欢使用with。然而,sketch.txt有一些场景,其中很少有行没有“:”,而很少有行有很多“:”,因此我总是想查找“:”,并在第一行拆分。这个示例也应该适用。str.replace()的第三个参数1将只替换行中第一个出现的:如果没有找到,字符串将按原样返回。