2017-02-16 2 views
0

基本タスク:URLリクエストをテキストに変換し、テキストファイル(ほぼ使用可能なCSV)にダンプします。Python:テキストファイル複数の行に異なる文字列を置き換えますか?

ゴール:クリーンなCSV。複数行で複数の文字を置き換えようとしています。

ブラケット、 ティルダ(〜)、 各行の末尾に余分なカンマがあります。

これを達成するための比較的簡単な例はありません。行ごとにサイクルして置き換えることができるものを探してください。

ご注意:私は、このファイルが時間の経過と共に大きくなるため、メモリにはやらないと考えています。以下は

ファイル作成されたコードである:ここでは

import urllib.request 
with urllib.request.urlopen(URL1) as response: 
    data = response.read() 
decoded_data = data.decode(encoding='UTF-8') 

str_data = str(decoded_data) 
saveFile = open("test.txt",'w') 
saveFile.write(str_data) 
saveFile.close() 

を最初の行は、フィールド名、2番目と3番目の行がレコードを表している、ファイルから単純化されたサンプルです。

[[ "F1"、 "F2"、 "F3"、 "F4"、 "F5"、 "F6"]、

[ "string11"、 "string12"、 "string13"、「S 〜ring14" 、 "string15"、 "string16"]、

[ "string21"、 "string22"、 "S〜のring23"、 "string24"、 "string25"、 "string26"]]

答えて

1

内の文字を置き換えるstripを使用することができます。削除する文字に任意の位置がある場合は、代わりにreplaceを使用してください(line.replace("~","")など)。 line.replace("~","").replace(",","").replace("[","")

あなたのために働くかもしれないもののだけで簡単にモックアップ:

with open("text.txt", 'r') as f: 
    with open("result.txt", 'w') as new_f: 
     for line in f: 
      new_line = line.strip(" [],\n\t\r").replace("~","") 
      print(new_line) 
      new_f.write(new_line+"\n") 

以来stripとは異なり、あなたは1回のreplaceの呼び出しで複数の文字を指定することはできませんが、あなたはこのように、それらをチェーンすることができ、ことに、注意してくださいティルダはどこでもかまいませんが、大括弧とコンマは一般的に最後に表示されます。 "\ n"、 "\ t"、 "\ r"、およびスペースはstripに追加されています。これらの文字は各行の最後に表示される可能性があります。

+0

はい、これがありました!完璧!ありがとう!:-)うわー。 – marucho21

+0

括弧がテキストファイルに入力されている元の理由がわかりました。URLは、データのテーブル(列や行など)を伝えるためのJSONに移動します。下の例では、修正を加えてコードを再掲載しましたが、上の "スクラバー"は修正されたコードではありません。 – marucho21

0

ます簡単なfor-loopを使用してファイルを反復処理することができます。そして、あなたは、文字列の先頭や末尾の文字を交換したい場合は、各ライン

file = open("text.txt", "r") 
clean_txt = "" 
for line in file: 
    line = line.replace("~", "").replace("[","").replace("]","") 
    line[len(line)-1] = "" #Replace the last character of the line. 
file.close 
w = open("text.txt", "w") 
w.write(clean_txt) 
w.close 
+0

入力いただきありがとうございます。実際には、ファイルのすべての内容が削除されます。私はこの方法を投稿してから投稿しました。私がそれを働かせたとき、それは最初の行で "手術を行う"だけでした。ファイルを通過する何かを探してください。 – marucho21

0
#!/usr/bin/env python3 

# Note, I used the print function as a way to visually confirm the code worked. 
# the URL_call will yield a byte that has serialized data for a basic table (columns and rows, where first row are column names -- just like Excel or SQL) 

URL_call = ("http://www.zzz.com/blabla.html") 

# URLIB module & function: the request has to be first decoded from UTF-8 
import urllib.request 
with urllib.request.urlopen(URL_call) as response: 
    URL_data = response.read() 

URL_data_decoded = URL_data.decode(encoding='UTF-8') 

# use json to convert decoded response into a python structure (from a JSON structure) 
import json 
URL_data_JSON = json.loads(URL_data_decoded) 

# pandas will transition the python data structure from a "list-like" array to a table. 
import pandas as pd 
URL_data_panda = pd.DataFrame(URL_data_JSON) 

# this will create the text (in this case a CSV) file 
URL_data_panda.to_csv("test.csv") 

# The file will need the first row removed (columns are indexed coming out of the panda) 

#determine line count 
num_lines = sum(1 for line in open("test.csv")) 

print(num_lines) 

# the zero position is assigned to the first row of text. Writing from the second row (indexed as 1) get the removal done. 
lines = open("test.csv").readlines() 
open("test2.csv","w").writelines(lines[1:(num_lines)]) 


# Changes the name of the first column from zero to a normalized name. 

import fileinput 

# Note, below you could setup a back-up file, in the file input, by adding an extra argument in the parens ("test2.csv", inplace=True, backup='.bak') 
with fileinput.FileInput("test2.csv", inplace=True) as file: 
    for line in file: 
     print(line.replace("0,", "REC_NUM,"), end='')