Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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_String_Text - Fatal编程技术网

Python 如何打开文件、转换字符串和写入新文件

Python 如何打开文件、转换字符串和写入新文件,python,string,text,Python,String,Text,我试图打开一个文本文件,删除某些后面有“]的单词,然后将新内容写入一个新文件。使用下面的代码,新的内容包含了我需要的内容,并且创建了一个新文件,但它是空的。我不明白为什么。我尝试了不同的缩进方式,并传入了编码类型,但没有成功。非常感谢您的帮助 import glob import os import nltk, re, pprint from nltk import word_tokenize, sent_tokenize import pandas import string import c

我试图打开一个文本文件,删除某些后面有“]的单词,然后将新内容写入一个新文件。使用下面的代码,新的内容包含了我需要的内容,并且创建了一个新文件,但它是空的。我不明白为什么。我尝试了不同的缩进方式,并传入了编码类型,但没有成功。非常感谢您的帮助

import glob
import os
import nltk, re, pprint
from nltk import word_tokenize, sent_tokenize
import pandas
import string
import collections

path = "/pathtofiles"

for file in glob.glob(os.path.join(path, '*.txt')):
    if file.endswith(".txt"):
        f = open(file, 'r')
        flines = f.readlines()
        for line in flines: 
            content = line.split() 

            for word in content:
                if word.endswith(']'):
                    content.remove(word)

            new_content = ' '.join(content)

            f2 = open((file.rsplit( ".", 1 )[ 0 ] ) + "_preprocessed.txt", "w")
            f2.write(new_content)
            f.close

“萤火虫”这个应该有用。如果你有问题,很乐意回答

import glob
import os

path = "/pathtofiles"

for file in glob.glob(os.path.join(path, '*.txt')):
    if file.endswith(".txt"):
        with open(file, 'r') as f:
            flines = f.readlines()
            new_content = []
            for line in flines: 
                content = line.split() 

                new_content_line = []

                for word in content:
                    if not word.endswith(']'):
                        new_content_line.append(word)

                new_content.append(' '.join(new_content_line))

            f2 = open((file.rsplit( ".", 1 )[ 0 ] ) + "_preprocessed.txt", "w")
            f2.write('\n'.join(new_content))
            f.close
            f2.close

对于内容中的单词:if word.endswith']':content.removeword在迭代时删除:badf.close不执行任何操作,并且缩进是错误的。如果由于执行了全局搜索,file.endswith.txt保证始终为真。您根本没有关闭f2,则应使用模式“a”打开文件进行写入。请参阅:。或者列出单词列表,然后使用WriteLines是否确定模式=w?在我的机器上工作'_ツ_/¯. 好吧,w和a之间的区别只是创建一个新文件和附加文件。OP似乎表示每次都想要一个新的文件,所以w对我来说更有意义@PeterDolan!我知道这是在做什么,为什么更好。然而,该文件对我来说仍然是空白的!我在mac电脑上工作,也在windows上试用过。还有什么我可能做错了吗?因此,出于某种原因,最终这对一些决赛有效,但不是全部…通过在r和w之后添加encoding='utf-8',它对所有文件都有效。有趣的是,也许你的文件中有一些奇怪的字符。很高兴听到它在工作-还有其他问题吗?