2013-06-13 49 views
0

我有这样的代码,通过在文本文件中的行像这样运行:去除神秘换行符蟒蛇

09824747 18 n 02 archer 0 bowman 0 003 @ 09640897 n 0000 ~ 10290474 n 0000 ~i 10718145 n 0000 | a person who is expert in the use of a bow and arrow

L = line.split() 
L2 = line.split('|') 
synset_offset = L[0] 
lex_filenum = L[1] 
ss_type = L[2] 
gloss = L2[1] 

他们这样,我打印这些出看起来像这样

print('''<http://example.org/#'''+synset_offset+'''><http://www.monnetproject.eu/lemon#lex_filenum> "'''+lex_filenum+'''". 
<http://example.org/#'''+synset_offset+'''> <http://www.monnetproject.eu/lemon#ss_type> "'''+ss_type+'''". 
<http://example.org/#'''+synset_offset+'''> <http://www.monnetproject.eu/lemon#gloss> "'''+gloss+'''".''') 

但由于某种原因发生换行后'''+gloss+'''

,看起来像这样

<http://example.org/#09824747> <http://www.monnetproject.eu/lemon#lex_filenum> "18". 
<http://example.org/#09824747> <http://www.monnetproject.eu/lemon#ss_type> "n". 
<http://example.org/#09824747> <http://www.monnetproject.eu/lemon#gloss> " a person who is expert in the use of a bow and arrow 
". 

我想删除断行,因为它不会允许文本进行,否则格式化

+0

而且 - 其他scritp HTML生成语言如PHP和JavaScript缺乏一个内置的字符串模板系统,并要求该组合您正在使用的引号和+符号(或。)。 Python的情况并非如此 - 如果您使用以下任一类型的字符串格式,您的HTML片段可以变得更具可读性两个数量级:http://docs.python.org/2/library/stdtypes.html#string-formatting – jsbueno

回答

4

.split()不带参数或None作为第一个参数首先除去周围的线的空白,但.split('|')不是

分裂之前明确地将其删除:

L2 = line.strip().split('|') 

以后:

gloss = L2[1].strip() 

.strip()删除所有前后空白。您可以更具体,只删除使用`.rstrip()从最终的换行符:

gloss = L2[1].rstrip('\n')