2012-12-19 190 views
7

我找到了大多數在線英文單詞列表,但換行符是unix-style(以Unicode編碼:UTF-8)。我發現它在這個網站上:http://dreamsteep.com/projects/the-english-open-word-list.html如何將LF轉換爲CRLF?

如何將換行符轉換爲CRLF,以便我可以遍歷它們?我將使用它們的程序遍歷文件中的每一行,因此這些單詞必須是每行一行。

這是文件的一部分:bitbackbitebackbiterbackbitersbackbitesbackbitingbackbittenbackboard

它應該是:

bit 
backbite 
backbiter 
backbiters 
backbites 
backbiting 
backbitten 
backboard 

如何將我的文件轉換爲這種類型的?注意:這是26個文件(每個字母一個),總共有80,000個字左右(所以程序應該非常快)。

我不知道從哪裏開始,因爲我從未使用過unicode。提前致謝!

在我的代碼使用rU作爲參數(如建議),與此:

with open(my_file_name, 'rU') as my_file: 
    for line in my_file: 
     new_words.append(str(line)) 
my_file.close() 

我得到這個錯誤:

Traceback (most recent call last): 
    File "<pyshell#5>", line 1, in <module> 
    addWords('B Words') 
    File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\Programming Class\hangman.py", line 138, in addWords 
    for line in my_file: 
    File "C:\Python3.3\lib\encodings\cp1252.py", line 23, in decode 
    return codecs.charmap_decode(input,self.errors,decoding_table)[0] 
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 7488: character maps to <undefined> 

誰能幫助我?

+0

你可能覺得這http://stackoverflow.com/questions/3891076/how-to-convert-windows-end-of-line-in-unix-end-of-line-cr-lf-to-如果有幫助 – dmi3y

+1

難道你不能讓你的程序能夠處理這兩種類型的行結束嗎? –

+0

@JamesMcLaughlin我已經有文字的列表的文件。另外,我從來沒有用過的Unicode(如說明),所以我不知道如何處理這些類型的結局。 –

回答

16

相反轉換的,你應該能夠使用Python的universal newline support剛打開文件:

f = open('words.txt', 'rU') 

(注U。)

+2

似乎這是現在棄用:https://docs.python.org/3.6/library/functions.html#open – cinatic

9

您可以使用字符串的替換方法。像

txt.replace('\n', '\r\n') 

編輯:
你的情況:

with open('input.txt') as inp, open('output.txt', 'w') as out: 
    txt = inp.read() 
    txt = txt.replace('\n', '\r\n') 
    out.write(txt) 
+0

,看我的答案在這裏:http://stackoverflow.com/a/43678795/3459910 – winklerrr

2

你d不需要轉換文件中的行尾以便能夠遍歷它們。正如NPE所建議的,只需使用python's universal newlines mode即可。

的UnicodeDecodeError錯誤發生,因爲你正在處理的文件編碼爲UTF-8,當你試圖將內容從字節的字符串通過str(line)解碼,Python是使用cp1252編碼,從文件中讀取的字節轉換轉換成Python 3字符串(即unicode代碼點序列)。但是,這些文件中的字節無法用cp1252編碼進行解碼,並且會導致UnicodeDecodeError。

如果將str(line)更改爲line.decode('utf-8'),則不應再獲取UnicodeDecodeError。查看Text Vs. Data Instead of Unicode Vs. 8-bit的書面瞭解更多詳情。

最後,你也可能會發現由Joel Spolsky的有用The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

相關問題