【问题标题】:Split large text file using keyword delimiter使用关键字分隔符拆分大文本文件
【发布时间】:2015-03-10 04:58:53
【问题描述】:

我正在尝试使用单词分隔符将大型文本文件拆分为较小的文本文件。我尝试搜索,但我只看到过在 x 行之后拆分文件的帖子。我对编程很陌生,但我已经开始了。我想遍历所有行,如果它以 hello 开头,它会将所有这些行放入一个文件中,直到到达下一个 hello。文件中的第一个单词是 hello。最终,我试图将文本放入 R 中,但我认为如果我先像这样拆分它会更容易。任何帮助表示赞赏,谢谢。

text_file = open("myfile.txt","r")
lines = text_file.readlines()
print len(lines)
for line in lines :
    print line
    if line[0:5] == "hello":

【问题讨论】:

标签: python r text split


【解决方案1】:

如果你正在寻找一个非常简单的逻辑,试试这个。

text_file = open("myfile.txt","r")
lines = text_file.readlines()
print len(lines)
target = open ("filename.txt", 'a') ## a will append, w will over-write
hello1Found = False
hello2Found = False

for line in lines :
    if hello1Found == True :  
        if line[0:5] == "hello":
            hello2Found = True
            hello1Found = False
            break ## When second hello is found looping/saving to file is stopped 
              ##(though using break is not a good practice here it suffice your simple requirement
        else: 
            print line #write the line to new file
            target.write(line)
    if hello1Found == False:
        if line[0:5] == "hello": ##find first occurrence of hello 
            hello1Found = True
            print line 
            target.write(line)      ##if hello is found for the first time write the 
                                ##line/subsequent lines to new file till the occurrence of second hello

【讨论】:

  • 同时在程序结束时关闭打开的文件。 target.close();text_file.close();
  • 这成功了!谢谢!然而,我确实做了一些小改动,很可能是因为我的问题可能不够清楚(对不起)。我摆脱了中断,并将其替换为: target = open("filename" + str(k) + ".txt"。其中 k 是一个整数,在每个循环后增加 1。这样它分成超过 2文件(我最终有 6009 个)
【解决方案2】:

我是 Python 新手。我刚刚在东北大学完成了地理信息系统的 Python 课程。这就是我想出的。

import os
import sys
import arcpy

def files():
    n = 0
    while True:
        n += 1
        yield open('/output/dir/%d.txt' % n, 'w')

pattern = 'hello'
fs = files()
outfile = next(fs)
filename = r'C:\output\dir\filename.txt'

with open(filename) as infile:
    for line in infile:
        if pattern not in line:
            outfile.write(line)
        else:
            items = line.split(pattern)
            outfile.write
            (items[0])
            for item in items:
                outfile = next(fs)
                outfile.write(item)

filename.close();outfile.close();

【讨论】:

    猜你喜欢
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多