【问题标题】:How to write a file and eliminate lines?如何编写文件并消除行?
【发布时间】:2017-10-31 23:52:30
【问题描述】:

我想从文件中读取不同的行,例如:

hello   I live in London.
hello   I study.

然后根据我要从文件中删除的第一个单词是什么。

我可以将哪个句子放在一个数组中吗?

【问题讨论】:

  • 你自己走了多远,你的问题到底是什么?
  • 请阅读How to Ask
  • 另外,python 中没有数组。对问题更具描述性。
  • 如果句子的开头只有我要查找的单词,我可以删除该行。如果前面有更多单词,则不会发生任何事情。

标签: python arrays file


【解决方案1】:

您可以将文件的全部内容读入内存(进入列表),选择您希望保留的行,然后将这些行写入一个新文件(如果您愿意,可以替换旧文件)。

例如:

old_lines = open("input.txt",'r').readlines() 
new_lines = []

for line in old_lines:
     words = line.split()
     if words[0] == 'hello': # if the first word is "hello", keep it.
         new_lines.append(line)

f = open("output.txt",'w')
for line in new_lines:
    f.write(line)

【讨论】:

  • 顺便问一下,我可以把短语的一个词替换为开头的那个吗?
  • 是的。您可以使用我使用过的split 方法,将一行按空格拆分为一个列表。 IE。 "Hello this is a".split() 返回["Hello","this","is","a"]。然后您可以访问任何列表成员,将它们更改为不同的单词,然后使用 '(space)'.join(list_var) 将列表重新转换为句子
  • 我想将句子的一个单词替换为开头的 hello 单词。我的问题是如何找到句子中的单词?
  • list_var 是什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 2020-08-07
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多