【问题标题】:Problems with Python's file.write() method and string handlingPython 的 file.write() 方法和字符串处理的问题
【发布时间】:2011-06-28 16:45:25
【问题描述】:

我此时遇到的问题(对 Python 不熟悉)是将字符串写入文本文件。我遇到的问题是字符串之间没有换行符,或者 每个 字符后都有换行符。要遵循的代码:

import string, io

FileName = input("Arb file name (.txt): ")

MyFile = open(FileName, 'r')

TempFile = open('TempFile.txt', 'w', encoding='UTF-8')

for m_line in MyFile:
    m_line = m_line.strip()
    m_line = m_line.split(": ", 1)
    if len(m_line) > 1:
        del m_line[0]
    #print(m_line)
    MyString = str(m_line)
    MyString = MyString.strip("'[]")
    TempFile.write(MyString)


MyFile.close()
TempFile.close()

我的输入如下所示:

1 Jargon
2 Python
3 Yada Yada
4 Stuck

我这样做时的输出是:

JargonPythonYada YadaStuck

然后我把源代码修改成这样:

import string, io

FileName = input("Arb File Name (.txt): ")

MyFile = open(FileName, 'r')

TempFile = open('TempFile.txt', 'w', encoding='UTF-8')

for m_line in MyFile:
    m_line = m_line.strip()
    m_line = m_line.split(": ", 1)
    if len(m_line) > 1:
        del m_line[0]
    #print(m_line)
    MyString = str(m_line)
    MyString = MyString.strip("'[]")
    #print(MyString)
    TempFile.write('\n'.join(MyString))


MyFile.close()
TempFile.close()

相同的输入,我的输出如下所示:

J
a
r
g
o
nP
y
t
h
o
nY
a
d
a

Y
a
d
aS
t
u
c
k

理想情况下,我希望每个单词出现在单独的一行上,前面没有数字。

谢谢,

马利H

【问题讨论】:

  • 你不能做MyString= str(m_line),因为这个指令创建了一个对象 m_line 的字符串表示,它是一个字符串列表,所以你得到一个以 [ 开头并以 ] 结尾的字符串,包括字符串列表的元素,也就是说,在它们周围加上 ',然后你必须去掉这些你自己创建的字符。相反,应用于 list 的 join() 会立即给出所需的结果。
  • 要消除字符串前面的数字,后面的字符用空格隔开,你可以line.partition(' ')[2] on line being '1 Jargon'

标签: python string list file


【解决方案1】:
fileName = input("Arb file name (.txt): ")
tempName = 'TempFile.txt'

with open(fileName) as inf, open(tempName, 'w', encoding='UTF-8') as outf:
    for line in inf:
        line = line.strip().split(": ", 1)[-1]

        #print(line)
        outf.write(line + '\n')

问题:

  1. str.split() 的结果是一个列表(这就是为什么当你将它转换为 str 时,你会得到 ['my item'])。

  2. write 不添加换行符;如果你想要一个,你必须明确地添加它。

【讨论】:

    【解决方案2】:

    你必须在每一行之后写下'\n',因为你要剥离原来的'\n'; 您使用'\n'.join() 的想法不起作用,因为它将使用\n 加入字符串,将其插入字符串的每个字符之间。您需要在每个名称后添加一个 \n

    import string, io
    
    FileName = input("Arb file name (.txt): ")
    
    with open(FileName, 'r') as MyFile:
        with open('TempFile.txt', 'w', encoding='UTF-8') as TempFile:
            for line in MyFile:
                line = line.strip().split(": ", 1)
                TempFile.write(line[1] + '\n')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多