繁体   English   中英

如何使用 python 将 add, , 添加到 an.txt 文件中的每个单词

[英]how to make add , , to every word in an .txt file with python

我有一个 long.txt 文件,里面有很多单词。 有点像这样

bosstones 
boston 
both 
bottom 
bowie 
bowl 

但我想在每一行的末尾和开头添加这个。 看起来像这样

,bosstones, 
,boston, 
 ,both, 
,bottom, 
,bowie, 
,bowl, 

那么我可以在 python 中这样做吗?

假设您有一个名为 a.txt 的文件,其中包含所有单词,您可以使用以下脚本创建一个新文件。

f = open('a.txt', 'r+')
data = f.read()
f.close()
g = open('new_a.txt', 'w+')
for d in data.splitlines():
    g.write(f',{d.strip()},\n')
g.close()
with open("yourTextFile.txt", "r") as f: data = f.read().split("\n") with open("yourOutput.txt", "w") as f: newdata = '' for line in data: newdata += ","+line+",\n" f.write(newdata)line in data:

我们需要在这里介绍几个不同的概念。

从文件中读取

要读取文件,首先需要打开它。 Python 为我们提供了很好的工具来管理它。 第一个是open ,它可以让您打开文件进行阅读。

open是一个带有两个参数的 function。 第一个是文件名。 第二个是您要打开它的“模式”。我们要从文件中读取,所以我们可以使用'r'

input_file = open('input.txt', 'r')

要管理文件,您可以使用with在上下文中打开它。 这听起来很复杂,但它实际上使事情变得容易得多。

with open('input.txt', 'r') as input_file:
    # Inside this block, we can do whatever we need to do with input_file

现在要从文件中读取数据,您可以使用几个函数,但readlines可能是最有意义的。 readlines function 返回一个包含文件中所有行的可迭代(列表)。 因此,您可以阅读文件中的所有文本并将其打印出来,如下所示:

with open('input.txt', 'r') as input_file:
    for line in input_file.readlines():
        print(line)

修改字符串

接下来你需要做的是修改一个字符串。 对于您的情况,最好的方法是使用f-string ,它可以让您格式化新字符串。 解释起来可能有点困难,所以我举个例子。

test1 = 'hello'
test2 = f'+{test1}+'
print(test2)  # Prints '+hello+'

f-string中,用大括号 ( '{}' ) 括起来的任何内容都被读取为变量并插入到字符串中。 非常有帮助!

您需要注意的其他事情是换行符 当您从文件中读入一行时,该行包含一个换行符( '\n' )。 你会想要删除它。 如果你不这样做,这就是发生的事情。

test1 = 'hello\n'
test2 = f'+{test1}+'
print(test2)
# Prints
# +hello
# +

'\n'字符实际上被打印并在 output 中创建一个新行。 不好,幸运的是:有一个 function 可以自动删除任何前导或尾随换行符: strip 我们可以修复上面的例子:

test1 = 'hello\n'
test1 = test1.strip()
test2 = f'+{test1}+'
print(test2)
# Prints
# +hello+

写入文件

最后,我们需要将修改后的字符串写入文件。 您仍然需要使用open打开文件,但您应该指定'w'作为 'write' 的第二个参数。 您仍然可以像以前一样使用上下文管理器。 要写入文件,您只需要使用write function。 该文件甚至不需要存在,如果不存在,Python 将自动创建它。

with open('output.txt', 'w') as output_file:
    output_file.write('Hello world!\n')
    output_file.write('You can write multiple lines!\n')

请注意,当我们写入 output 时,我们需要重新添加换行符。

把它们放在一起

您可以通过多种方式将所有这些放在一起,但我可能会这样做。

with open('input.txt', 'r') as input_file:
    with open('output.txt', 'w') as output_file:
        for line in input_file.readlines():
            line = line.strip()
            line = f',{line},\n'
            output_file.write(line);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM