簡體   English   中英

函數的結果未更新?

[英]Function's result is not updated?

我是最近才開始學習Python的。 我正在嘗試一段執行一些簡單文本編輯的代碼。 該程序假設采用UTF-8編碼的txt文件,請確保從第二行開始將所有內容縮進1個空格,並刪除所有可能的雙精度或三重空格。

我的計划是,從txt文件中讀取信息並將其存儲在列表中。 然后,我將處理列表中的元素,然后最后將它們重寫回文件(尚未實現)。我認為自動縮進代碼的第一部分正在工作。

但是,對於檢測和刪除不需要的空格的代碼,我嘗試使用function方法,但我認為它是可行的。 但是,當我在主體代碼中測試列表內容時,內容似乎沒有發生變化(原始狀態)。 我做錯了什么?

為了給出示例文件的想法,我將發布我嘗試處理的txt文件的一部分

原版的:

  There   are various kinds of problems concerning  human rights. Every day we hear news reporting on human rights violation. Human rights NGOs (For example, Amnesty International or Human Rights Watch) have been trying to deal with and resolve these problems in order to restore  the human rights of individuals. 

預期:

 There are various kinds of problems concerning human rights. Every day we hear news reporting on human rights violation. Human rights NGOs (For example, Amnesty International or Human Rights Watch) have been trying to deal with and resolve these problems in order to restore the human rights of individuals. 

我的代碼如下

import os
os.getcwd()
os.chdir('D:')
os.chdir('/Documents/2011_data/TUFS_08_2011')

words = []

def indent(string):
    for x in range(0, len(string)):
        if x>0:
            if string[x]!= "\n":
                if string[x][0] != " ":              
                    y = " " + string[x] 

def delete(self):
    for x in self:
        x = x.replace("    ", "   ")
        x = x.replace("   ", "  ")
        x = x.replace("  ", " ")
        print(x, end='')
    return self       

with open('dummy.txt', encoding='utf_8') as file:
    for line in file:
        words.append(line)
    file.close()
    indent(words)
    words = delete(words)

for x in words:
    print(x, end='') 

您的delete函數遍歷一個列表,將每個字符串分配給x,然后依次使用各種替換結果重新分配x。 但是它永遠不會將結果放回到列表中,而該列表將保持不變。

最簡單的方法是建立一個包含修改結果的新列表,然后返回該列表。

def delete(words):
    result = []
    for x in words:
        ... modify...
        result.append(x)
    return result

(請注意,使用名稱“ self”不是一個好主意,因為這意味着您使用的是對象方法,而實際上不是。)

您可以使用split()join輕松刪除空格;

In [1]: txt = '  This  is a text   with      multiple   spaces.   '

使用字符串的split()方法可為您提供不帶空格的單詞列表。

In [3]: txt.split()
Out[3]: ['This', 'is', 'a', 'text', 'with', 'multiple', 'spaces.']

然后,您可以在單個空格處使用join方法;

In [4]: ' '.join(txt.split())
Out[4]: 'This is a text with multiple spaces.'

如果您想在前面多留一個空格,請在列表中插入一個空字符串;

In [7]: s = txt.split()

In [8]: s
Out[8]: ['This', 'is', 'a', 'text', 'with', 'multiple', 'spaces.']

In [9]: s.insert(0, '')

In [10]: s
Out[10]: ['', 'This', 'is', 'a', 'text', 'with', 'multiple', 'spaces.']

In [11]: ' '.join(s)
Out[11]: ' This is a text with multiple spaces.'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM