从文件中删除每个第n个单词

时间:2011-02-14 01:22:35

标签: python

该函数应该返回文件中的其余单词,而不是第n个单词。 我已经开放,阅读和关闭文本文件,但我一直在努力弄清楚剩下的。我尝试使用追加但很快意识到这不是解决问题的方法。

到目前为止,我的编码失败了:

def message(fname, n):

    infile = open(fname,'r')
    mess = infile.read()
    infile.close()
    mess.append('')
    return mess

所以它应该从文件中返回其余的单词,而不是第n个单词。

3 个答案:

答案 0 :(得分:4)

要删除每个n th 字,伪代码将读取每个字并将它们全部写出来,除了wordnumber modulo n等于0的字。

换句话说:

nth = 7
wordnumber = 0
while not end-of-file:
    read word
    wordnumber = wordnumber + 1
    if wordnumber % nth is not 0:
        write word

真的是这样的。但是不要错误地认为这是Python。我的伪代码看起来非常像Python,因为该语言非常适合使用,但您不能将其插入Python解释器并期望它按原样工作。

当然,将它改编成Python或任何其他正常语言(在whileif语句的语言中是正常的,不应该太难了)那些更具说明性的人。)

答案 1 :(得分:2)

可以将整个文件读入列表,并使用del语句删除每个第n项。

def remove_every_nth_word_from_file(filename, n):
    with open(filename) as f:
        words = f.read().split()
        del words[n - 1::n]
    return words

f.read()函数将整个文件作为字符串读取; split()函数用空格分割这个字符串; words [n - 1 :: n]是一个列表切片,表示从第(n-1)个位置开始,包括每个第n个项目; del语句从列表中删除此切片。

答案 2 :(得分:0)


def all_but_n(file,num):
  rf=[]    #rf is the list containing words for the returned file
  n=num
  f=open(file,'r')
  i=0#for indexing the file
  for line in f:
    line=line.strip('\n').split(' ')
    for word in line:
      if n!=i+1:
        rf.append(word)
      else:
        n=n+num
      i=i+1
  return rf

all_but_n('',3)

你当然可以使用列表推导来提高速度。我以这种方式写了all_but_n(),这样你就可以理解发生了什么

相关问题