Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python分析制表符或空格分隔的文件_Python - Fatal编程技术网

使用Python分析制表符或空格分隔的文件

使用Python分析制表符或空格分隔的文件,python,Python,我有一个文件,其中每个单词由单个空格或制表符或多个空格分隔: e、 g address1.txt: Bob lives in Boston Sam lives in Houston Jay lives in Ruston Bill lives in Atlanta 我想将文件另存为address2.txt,其中每个单词用制表符分隔 如何使用Python实现这一点 有什么帮助吗 谢谢 RioDo'\t'。在文件的每一行加入(line.split

我有一个文件,其中每个单词由单个空格或制表符或多个空格分隔:

e、 g

address1.txt:

Bob lives in Boston
Sam lives    in Houston
Jay       lives in Ruston
Bill        lives in           Atlanta
我想将文件另存为address2.txt,其中每个单词用制表符分隔

如何使用Python实现这一点

有什么帮助吗

谢谢
Rio

Do
'\t'。在文件的每一行加入(line.split())
。这是因为不带参数的
split()
会在任何空格序列上断开行。

Do
'\t'.join(line.split())
在文件的每一行上。这是因为不带参数的
split()
会在任何空格序列上打断行。

使用
split
在空格上拆分,然后使用
join
将单词与制表符重新组合在一起

with open('address1.txt') as fin, open('address2.txt','w') as fout:
  for line in fin:
    fout.write( "\t".join(line.split()) + "\n" )

使用
split
在空白处拆分,然后使用
join
将单词与制表符重新组合在一起

with open('address1.txt') as fin, open('address2.txt','w') as fout:
  for line in fin:
    fout.write( "\t".join(line.split()) + "\n" )
另一种方式:

#!/usr/bin/python

with open('address1.txt', 'r') as ro, \
    open('address2.txt', 'a') as rw:
      for line in ro.readlines():
          ls = line.strip().split()
          rw.write('\t'.join(ls) + '\n')
另一种方式:

#!/usr/bin/python

with open('address1.txt', 'r') as ro, \
    open('address2.txt', 'a') as rw:
      for line in ro.readlines():
          ls = line.strip().split()
          rw.write('\t'.join(ls) + '\n')

这与我的答案有什么实质性的不同?with将确保关闭它。这与我的答案有什么实质性的不同?with将确保关闭它。我还建议使用
上下文管理器来处理打开的文件。当然,人们不会使用
readlines()
。使用fin:
中的行的
迭代该文件是一种方法。编辑以合并您的改进。谢谢我还建议使用
上下文管理器来处理打开的文件。当然,人们不会使用
readlines()
。使用fin:
中的行的
迭代该文件是一种方法。编辑以合并您的改进。谢谢