簡體   English   中英

如何在python中使用len()刪除特定單詞?

[英]How to delete a specific word by using len() in python?

我在這里看到太多問題沒有人回答我的問題。 我有文本文件ckb.txt

چ
چۆنی
باشی
سوپاس
ئاسمان
یاسا
دەنگ
چنار
کورستانی گەورە

我想刪除len()超過 4 個字符的任何行,我寫了這個簡單的代碼但不起作用,有什么建議或提示嗎?

    import arabic_reshaper
    from bidi.algorithm import get_display
    import unicodedata

    with open("ckb.txt", 'r+', encoding='utf-8') as f:
    
        g = f.readlines()
        for line in g:
            print(get_display(arabic_reshaper.reshape(line)))
            print(len(line))
            if len(line) > 4:
                del line

基於此: 如何刪除文件中的特定行?

import arabic_reshaper
from bidi.algorithm import get_display
import unicodedata

with open("ckb.txt", 'r+', encoding='utf-8') as f:

    g = f.readlines()
    f.seek(0)
    for line in g:
        print(get_display(arabic_reshaper.reshape(line)))
        print(len(line))
        if len(line.strip("\n")) <= 4:
            f.write(line)
    f.truncate()
with open("ckb.txt", 'r+', encoding='utf-8') as f:
    lines = f.readlines()

with open("ckb.txt", 'w+', encoding='utf-8') as f:
    lines = list(filter(lambda x: len(x) <= 4, lines))
    f.writelines(lines) 

這應該可以解決問題:

lines = [line for line in open("ckb.txt", 'r+', encoding='utf-8').readlines() if len(line) < 4]

導入庫后直接使用。

如果要在原始文件中寫回這些行,請使用:

with open("ckb.txt", 'w', encoding='utf-8'):
    f.write('\n'.join(lines))

暫無
暫無

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

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