Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.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 使用文本文件和列表重新创建句子_Python - Fatal编程技术网

Python 使用文本文件和列表重新创建句子

Python 使用文本文件和列表重新创建句子,python,Python,我对Python比较陌生,目前正在开发一个压缩程序,该程序使用包含列表中单词位置的列表和组成句子的单词列表。到目前为止,我已经在两个函数中编写了我的程序,第一个函数;'“压缩”,获取组成句子的单词以及这些单词的位置。我的第二个函数叫做“recreate”,这个函数使用列表来重新创建句子。然后,重新创建的senetence存储在名为recreate.txt的文件中。我的问题是,单词的位置和组成句子的单词没有被写入各自的文件中,“重新创建”文件也没有被创建和写入。任何帮助都将不胜感激。谢谢:) 更

我对Python比较陌生,目前正在开发一个压缩程序,该程序使用包含列表中单词位置的列表和组成句子的单词列表。到目前为止,我已经在两个函数中编写了我的程序,第一个函数;'“压缩”,获取组成句子的单词以及这些单词的位置。我的第二个函数叫做“recreate”,这个函数使用列表来重新创建句子。然后,重新创建的senetence存储在名为recreate.txt的文件中。我的问题是,单词的位置和组成句子的单词没有被写入各自的文件中,“重新创建”文件也没有被创建和写入。任何帮助都将不胜感激。谢谢:)


更新 我已经修复了除recreate函数之外的所有其他问题,recreate函数不会生成“recreate”文件,也不会用单词重新创建句子 它用位置重现句子

def recreate(compress): #function that will be used to recreate the compressed sentence.
    compress()
    num = list()
    wds = list()

    with open("words.txt", "r") as txt: #with statement opening the word text file
        for line in txt: #iterating over each line in the text file.
            words += line.split() #turning the textfile into a list and appending it to num

    with open("tsk3pos.txt", "r") as txt:
        for line in txt:
            num += [int(i) for i in line.split()]

    recreate = ' '.join(wds[pos] for pos in num)

    with open("recreate.txt", "wt") as txt:
        txt.write(recreate) 

    main()



def main():
    print("Do you want to compress an input or recreate a compressed input?")
    user = input("Type 'a' if you want to compress an input. Type 'b' if you wan to recreate an input").lower()
    if user not in ("a","b"):
        print ("That's not an option. Please try again")
    elif user == "a":
        compress()
    elif user == "b":
        recreate(compress)
    main()

main()
更简单(但效率更低)的方法:

 recreate_file_object  =  open ( "C:/FullPathToWriteFolder/recreate.txt"   ,   "w"   )
 recreate_file_object.write ( recreate ) 
 recreate_file_object.close ( )

首先,不要使用
变量=打开(文件)
,使用
上下文管理器。你似乎在来回切换…谢谢你的回复。我已将all variable=open(file)更改为“with”上下文管理器,并检查了代码,但仍然无法找出任何问题@mattdmow“在此处输入代码”是什么意思?还有其他代码没有显示吗?因为当前您正在定义函数,但从未调用它们。此外,您的
语句.lower()
没有分配给任何对象。感谢您的回复。输入不应该放在那里的代码@user234461谢谢你的回复。这是否应该解决未创建重新创建文件的问题@非常感谢。我会试试的@RasikhJ
 recreate_file_object  =  open ( "C:/FullPathToWriteFolder/recreate.txt"   ,   "w"   )
 recreate_file_object.write ( recreate ) 
 recreate_file_object.close ( )