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

0 投票
3 回答
3473 浏览
提问于 2025-04-16 11:46

这个函数应该返回文件中所有的单词,除了第n个单词。我已经掌握了打开、读取和关闭文本文件的基本操作,但在接下来的部分我一直搞不定。我尝试过使用追加的方式,但很快意识到这样做不太对。

这是我到目前为止的失败代码:

def message(fname, n):

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

所以它应该返回文件中所有的单词,除了第n个单词。

3 个回答

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() 函数的,这样你就能明白发生了什么。

4

要删除每第 n 个单词,伪代码的思路是读取每一个单词,然后把所有单词写出来,除了那些位置是 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 解释器里就指望它能正常工作。

当然,把它改成 Python 或者其他常见的编程语言应该不难(这里的“常见”指的是那些有 whileif 语句的语言,而不是那些更偏向声明式的语言)。

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语句则是用来从列表中删除这个切片的。

撰写回答