2013-06-12 41 views
0

我有一個txt文件,其中提供了大量的信息。 我想讀取和存儲'狀態'部分。閱讀每行的txt文件的特定部分

例子:

id........username...... status......language .......image 

11111 abcdefg Man Utd won for the second time ENG img1244 

11112 abcdaaa Man Utd won for the third time ENG img1245 

11113 abcdbbb Man Utd won for the fourth time ENG img1246 

11114 abcdccc Man Utd won for the fifth time ENG img1247 

11115 abcdddd Man Utd won for the sixth time ENG img1248 

And what I should obtain is the following 

Man Utd won for the second time 

Man Utd won for the third time 

Man Utd won for the fourth time 

Man Utd won for the fifth time 

Man Utd won for the sixth time 

我想要做的就是從用戶名字符串數據存儲到「ENG」串什麼。

感謝您的幫助。

回答

0

你可以用一個簡單的perl腳本來做到這一點。對於windows,可以從activestate下載perl。 Linux通常已經安裝了perl。

要使用:

  1. 安裝(或已經)perl的
  2. 複製下面的腳本到一個文本文件
  3. 保存使用您選擇的一個簡單的名字與特等的擴展名的文件(例如:parser.pl)
  4. 保存源文件在同一目錄中,並命名爲 'input.txt的'
  5. 從cmd窗口執行:perl的parser.pl
  6. 腳本的結果將在名爲'output.txt'(在同一目錄中)的文件中創建,並且如果該文件存在將被覆蓋。

腳本假設:

  1. 文本您尋找與男人還是女人
  2. 開始的ENG文本不會出現在你正在尋找的文字,只在最後。
  3. 語言文字總是ENG。如果不與替代ENG:上線18

腳本(ENG |其他1 | |其它2 ETC):!

在/ usr/local/bin中/ perl的

使用嚴格的;

unless(open(INFILE, "input.txt")){ 
    print "Unable to open input file input.txt for reading, possible reason: $!\n"; 
    exit; 
}; 

unless(open(OUTFILE, ">output.txt")){ 
    print "Unable to open output file output.txt for writing, possible reason: $!\n"; 
    exit; 
}; 

my $x = 1; 
foreach my $line (<INFILE>){ 
    print "$line"; 
    if($line =~ /((?:Wom|M)an.*) ENG/){ 
     print OUTFILE $1."\n"; 
    }else{ 
     print "No match found on line $x\n"; 
    } 
    $x++; 
} 

close(INFILE); 
close(OUTFILE); 
exit; 
+0

謝謝您的回答和幫助,但如果我沒有固定的beginging句子,如「Man」或「Woman」,該怎麼辦?它與everyline不同,我所知道的是用戶名以數字(0-9)結尾。 它是這樣的: 11111 abcdef9曼聯第二次獲勝ENG img1244 –

+0

我想出的腳本並不關心任何人或女人部分之前的任何內容,並且將適用於您擁有的所有文本語法示例給出。運行它反對你的實際文件,讓我知道它是如何工作的。 – Drew

+0

好的,我解決了我的問題。非常感謝。 –