簡體   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