简体   繁体   English

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

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

I have a long.txt file with a lot of words in it.我有一个 long.txt 文件,里面有很多单词。 That kinda looks like this有点像这样

bosstones 
boston 
both 
bottom 
bowie 
bowl 

but i want to add this, at the end and the start of every line.但我想在每一行的末尾和开头添加这个。 That would look like this看起来像这样

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

So can i do that in python?那么我可以在 python 中这样做吗?

Consider you have a file named a.txt which has all the words, you can create a new file using the following script.假设您有一个名为 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:

There's a few different concepts we'll need to cover here.我们需要在这里介绍几个不同的概念。

Reading from a file从文件中读取

To read from a file, first you need to open it.要读取文件,首先需要打开它。 Python gives us good tools to manage this. Python 为我们提供了很好的工具来管理它。 The first is open , which lets you open the file for reading.第一个是open ,它可以让您打开文件进行阅读。

open is a function that takes two parameters. open是一个带有两个参数的 function。 The first is the name of the file.第一个是文件名。 The second is the "mode" that you want to open it in. We want to read from the file, so we can use 'r' .第二个是您要打开它的“模式”。我们要从文件中读取,所以我们可以使用'r'

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

To manage the file, you can open it in a context using with .要管理文件,您可以使用with在上下文中打开它。 This sounds complicated, but it actually makes things much easier.这听起来很复杂,但它实际上使事情变得容易得多。

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

Now to read the data from the file, there are several functions you can use, but readlines probably makes the most sense.现在要从文件中读取数据,您可以使用几个函数,但readlines可能是最有意义的。 The readlines function returns an iterable (a list) that contains all the lines in your file. readlines function 返回一个包含文件中所有行的可迭代(列表)。 So you can read all the text in your file and print it out like so:因此,您可以阅读文件中的所有文本并将其打印出来,如下所示:

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

Modifying strings修改字符串

The next thing you'll need to be able to do is modify a string.接下来你需要做的是修改一个字符串。 For your case, the best way to do that is to use f-string , which let you format new strings.对于您的情况,最好的方法是使用f-string ,它可以让您格式化新字符串。 It can be a bit difficult to explain, so I'll give an example.解释起来可能有点困难,所以我举个例子。

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

In an f-string , anything enclosed in curly braces ( '{}' ) is read as a variable and inserted into the string.f-string中,用大括号 ( '{}' ) 括起来的任何内容都被读取为变量并插入到字符串中。 Very helpful!非常有帮助!

Something else you'll need to watch out for is newline characters .您需要注意的其他事情是换行符 When you read in a line from the file, the line includes a newline character ( '\n' ).当您从文件中读入一行时,该行包含一个换行符( '\n' )。 You'll want to remove this.你会想要删除它。 If you don't, here's what happens.如果你不这样做,这就是发生的事情。

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

The '\n' character actually gets printed and creates a new line in the output. '\n'字符实际上被打印并在 output 中创建一个新行。 No good, Luckily: there is a function to automatically remove any leading or trailing newline characters: strip .不好,幸运的是:有一个 function 可以自动删除任何前导或尾随换行符: strip We can fix the above example:我们可以修复上面的例子:

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

Writing to a file写入文件

Lastly, we'll need to write the modified string out to a file.最后,我们需要将修改后的字符串写入文件。 You still need to open the file with open , but instead you should specify 'w' as the second parameter for 'write'.您仍然需要使用open打开文件,但您应该指定'w'作为 'write' 的第二个参数。 You can still use a context manager just like before.您仍然可以像以前一样使用上下文管理器。 To write to the file, you just need to use the write function.要写入文件,您只需要使用write function。 The file doesn't even need to exist, if it doesn't, Python will automatically create it.该文件甚至不需要存在,如果不存在,Python 将自动创建它。

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

Note that we need to add the newline characters back in when we write to the output.请注意,当我们写入 output 时,我们需要重新添加换行符。

Putting it all together把它们放在一起

You can put this all together a number of ways, but I'd probably do it like this.您可以通过多种方式将所有这些放在一起,但我可能会这样做。

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