2012-08-08 46 views
0

因此,我已经有了将所有带有数字的单词从文本中取出的代码,现在我需要做的就是将文本全部放在一行中。我需要使输出成为一行

with open("lolpa.txt") as f: 
    for word in f.readline().split(): 
     digits = [c for c in word if c.isdigit()] 
     if not digits: 
      print(word) 

拆分使词语全部位于不同的列中。 如果我拿出.split(),它会输入没有数字的单词,从字面上只是从单词中取出数字,并将每个字母放在不同的列中。

编辑:是的,print(word,end=" ")的作品,谢谢。但是我也希望脚本现在只读取一行。它不能读取第2行或第3行上的任何内容。

第二个问题是脚本只读取第一行。因此,如果在第一行输入将

i li4ke l0ke like p0tatoes potatoes 
300 bla-bla-bla 00bla-bla-0211 

输出将

i like potatoes 
+0

在这里看到了答案:http://stackoverflow.com/a/8914173/24718 – monkut 2012-08-08 02:51:45

+0

有什么输入你的预期输出是什么? – 2012-08-08 02:57:30

+0

@AshwiniChaudhary输入是“i li4ke l0ke like pt土豆土豆”,并在下一行“300 bla-bla-bla 00bla-bla-0211”中。问题是没有显示第二行。 – Kichrootra 2012-08-08 03:14:58

回答

5

在Python v 3.x中,你会使用

print(word, end='') 

避免换行。

在Python 2.x的v

print word, 

你使用逗号你要打印的项目结束。注意,与V3,你会得到连续打印

之间 一个空格

注意print(word),不会阻止以V 3.x的换行符

-

更新基于在原来的职位重新编码问题编辑:

随着输入:

i li4ke l0ke like p0tatoes potatoes 
300 bla-bla-bla 00bla-bla-0211 

验证码:

def hasDigit(w): 
    for c in w: 
     if c.isdigit(): 
     return True 
    return False 

with open("data.txt") as f: 
    for line in f: 
     digits = [w for w in line.split() if not hasDigit(w)] 
     if digits: 
      print ' '.join(digits) 
#   break  # uncomment the "break" if you ONLY want to process the first line  

WIL升产所有的“字”不包含数字:

i like potatoes 
bla-bla-bla <-- this line won't show if the "break" is uncommented above 

职位是有点不清楚,如果你想处理文件的第一行,,如果问题是你的脚本只处理第一行。该解决方案可以以任何方式工作,具体取决于break语句是否被注释掉。

+0

谢谢!对不起,如果我讨厌,但我怎么启用多行? – Kichrootra 2012-08-08 02:54:53

+0

@Kichrootra我不知道我理解你的问题(还有,你使用的是什么版本的Python?) – Levon 2012-08-08 02:55:39

+0

我正在使用Python 3.2。 问题是脚本只能用1行,这意味着如果我在文本中跳过一行,它将不会显示它。 – Kichrootra 2012-08-08 02:57:25

0

如果你使用python 3.x中,你可以这样做:

print (word,end="") 

到压制新行 - python 2.x使用有点奇怪的语法:

print word, #trailing comma 

或者,使用sys.stdout.write(str(word))。 (这适用于Python 2.x和3.x)。

0
with open("lolpa.txt") as f: 
    for word in f.readline().split(): 
     digits = [c for c in word if c.isdigit()] 
     if not digits: 
      print word, 
    print 

不是,print的末尾。

0

您可以使用join()

with open("lolpa.txt") as f: 
    print ' '.join(str(x.split()) for x in f if not [c for c in x.split() if c.isdigit()])   

使用一个简单的for循环:

import sys 
with open("data.txt") as f: 
    for x in f:    #loop over f not f.readline() 
     word=x.split() 
     digits = [c for c in word if c.isdigit()] 
     if not digits: 
      sys.stdout.write(str(word)) #from mgilson's solution