Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 无法正确保存文件_Python 3.x_File - Fatal编程技术网

Python 3.x 无法正确保存文件

Python 3.x 无法正确保存文件,python-3.x,file,Python 3.x,File,我有一个文本文件,其中包含一个关于一个故事的文本,我想找到一个单词“like”,然后得到后面的下一个单词,并调用一个函数来查找该单词的同义词。这是我的密码: file = 'File1.txt' with open(file, 'r') as open_file: read_file = open_file.readlines() output_lines = [] for line in read_file: words = line.split()

我有一个文本文件,其中包含一个关于一个故事的文本,我想找到一个单词“like”,然后得到后面的下一个单词,并调用一个函数来查找该单词的同义词。这是我的密码:

file = 'File1.txt'
with open(file, 'r') as open_file:
    read_file = open_file.readlines()
    output_lines = []        

for line in read_file:
    words = line.split()
    for u, word in enumerate(words):
        if 'like' == word:
            next_word = words[u + 1]
            find_synonymous(next_word )

    output_lines.append(' '.join(words))
    with open(file, 'w') as open_file:
        open_file.write(' '.join(words)) 

我唯一的问题是文字本身,因为当我写一个包含单词(like)的句子时,它是有效的(
,例如“我喜欢电影”
)。但是当我有一个包含很多句子的文件并运行代码时,它会删除所有文本。有人知道问题出在哪里吗

你有几个问题
find\u synonymous(下一个单词)
不会替换列表中的单词,因此最多只能返回原始文本。在
for
循环中,您确实打开了(文件“w”),因此每行都会覆盖该文件
next\u word=words[u+1]
如果
like
恰好是行中的最后一个单词,并且您不处理喜欢的东西在下一行继续的情况,则会引发索引错误

在本例中,我跟踪一个“is_like”状态。如果某个单词处于like状态,则会对其进行转换。这样,您就可以处理跨行拆分的句子,而不必担心索引错误。列表将写入循环外部的文件中

file = 'File1.txt'
with open(file, 'r') as open_file:
    read_file = open_file.readlines()

output_lines = []        
is_liked = False

for line in read_file:
    words = line.split()
    for u, word in enumerate(words):
        if is_liked:
            words[u] = find_synonymous(word)
            is_liked = False
        else:
            is_liked = 'like' == word
    output_lines.append(' '.join(words) + '\n')

with open(file, 'w') as open_file:
    open_file.writelines(output_lines)