我需要使输出在一个lin中

2024-06-16 12:28:49 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我已经有了从文本中提取所有带有数字的单词的代码,现在我所要做的就是把文本全部放在一行中。你知道吗

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

Tags: 代码in文本脚本forif数字单词
3条回答

在pythonv3.x中

print(word, end='')

为了避免出现新的情况。你知道吗

在pythonv2.x中

print word,

在打印的项目末尾使用逗号。请注意,与v3不同的是,在连续打印之间会有一个空格

注意,print(word),不会阻止v3.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 

将产生所有不包含数字的“单词”:

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

注:

如果您只想处理文件的第一行,或者如果问题是您的脚本只处理了文件的第一行,那么post有点不清楚。此解决方案可以以任何方式工作,这取决于break语句是否被注释掉。你知道吗

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的末尾。你知道吗

如果您使用的是Python3.x,则可以执行以下操作:

 print (word,end="")

为了抑制换行符--Python2.x使用了有点奇怪的语法:

 print word,  #trailing comma

或者,使用sys.stdout.write(str(word))。(这对Python2.x和3.x都适用)。你知道吗

相关问题 更多 >