簡體   English   中英

如何刪除.txt中以空格分隔的列

[英]How to remove space delimited columns in .txt

我有一個大的以空格分隔的.txt文件(大約50 MB),文件的結構如下所示。 我想擺脫前8個空格分隔的列。

L1045 +++$+++ u0 +++$+++ m0 +++$+++ BIANCA +++$+++ They do not!
L1044 +++$+++ u2 +++$+++ m0 +++$+++ CAMERON +++$+++ They do to!
L985 +++$+++ u0 +++$+++ m0 +++$+++ BIANCA +++$+++ I hope so.
L984 +++$+++ u2 +++$+++ m0 +++$+++ CAMERON +++$+++ She okay?
L925 +++$+++ u0 +++$+++ m0 +++$+++ BIANCA +++$+++ Let's go.
L924 +++$+++ u2 +++$+++ m0 +++$+++ CAMERON +++$+++ Wow
L872 +++$+++ u0 +++$+++ m0 +++$+++ BIANCA +++$+++ Okay -- you're gonna need to learn how to lie.

所需的輸出(以.txt為單位):

They do not!
They do to!
I hope so.
She okay?
...

如何在Python 2.7或3.4(請指定版本),R或使用linux命令行中做到這一點? 謝謝!

在我的Linux系統(Ubuntu 12.04)上,這個工作正常:

cut -f 9- -d " " tmp.tmp >newfile.out

-f 9-向前指定字段9; -d " "指定以空格分隔。

我的猜測是,這非常快(因為cut正是用於此目的的工具)。 可能可以使用幾行Python來完成,但可能會慢一些(?); 在R中執行此操作可能會很慢/效率低下。

R方法:

txt <- "L1045 +++$+++ u0 +++$+++ m0 +++$+++ BIANCA +++$+++ They do not!
L1044 +++$+++ u2 +++$+++ m0 +++$+++ CAMERON +++$+++ They do to!
L985 +++$+++ u0 +++$+++ m0 +++$+++ BIANCA +++$+++ I hope so.
L984 +++$+++ u2 +++$+++ m0 +++$+++ CAMERON +++$+++ She okay?
L925 +++$+++ u0 +++$+++ m0 +++$+++ BIANCA +++$+++ Let's go.
L924 +++$+++ u2 +++$+++ m0 +++$+++ CAMERON +++$+++ Wow
L872 +++$+++ u0 +++$+++ m0 +++$+++ BIANCA +++$+++ Okay -- you're gonna need to learn how to lie."

txt_obj <- readLines(textConnection(txt))
txt8 <- gsub( "^(([^ ]+[ ]){8})", "", txt_obj)
txt8
#----------
[1] "They do not!"                                  
[2] "They do to!"                                   
[3] "I hope so."                                    
[4] "She okay?"                                     
[5] "Let's go."                                     
[6] "Wow"                                           
[7] "Okay -- you're gonna need to learn how to lie."

使用Python slice可以很容易地做到這一點:

with open('in_file') as in_f:
    with open('out_file', 'w') as out_f:
        for i in [i.strip() for i in in_f if i != '\n']:
            out_f.write(' '.join(i.split()[8:]) + '\n')

這將刪除所有字符,直到最后一個+++

sed 's/.*+++[[:blank:]]\+//' file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM