简体   繁体   English

在split()中读取文件中的字符串

[英]Reading strings in file upon split()

Content of the file with name sketch1.txt 名称为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!

Code: 码:

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")

Result: Worked once, but not every time i ran 结果:工作一次,但不是每次都运行

---- 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.

Error: In most cases i end up receiving just a print statement 错误:在大多数情况下,我最终只会收到打印声明

  ---- read all---

There seems to be some code missing in your example. 您的示例中似乎缺少一些代码。 For example, I don't understand why you can loop over data without it having been defined in the scope of the for loop (it's only defined inside the read_file function, which is never called). 例如,我不明白为什么没有在for循环的范围内定义数据(仅在read_file函数内部定义,从未调用过)就可以遍历数据。 Also, the code is unnecessarily complicated, so unless there's any specific way of doing it with split, I'd do as follows: 另外,代码不必要地复杂,因此,除非有任何特定的拆分方法,否则我将执行以下操作:

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

This will also close the file after you have finished reading it (due to the with statement). 阅读完文件后(由于with语句),这还将关闭文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM