2012-08-15 59 views
9

Tôi đang cố gắng đọc văn bản từ một tệp văn bản, đọc dòng, xóa các dòng có chứa chuỗi cụ thể (trong trường hợp này là 'xấu' và 'nghịch ngợm'). Mã tôi đã viết như sau:Xóa các dòng có chứa chuỗi nhất định

infile = file('./oldfile.txt') 

newopen = open('./newfile.txt', 'w') 
for line in infile : 

    if 'bad' in line: 
     line = line.replace('.' , '') 
    if 'naughty' in line: 
     line = line.replace('.', '') 
    else: 
     newopen.write(line) 

newopen.close() 

Tôi đã viết như thế này nhưng không hiệu quả.

Một điều quan trọng là, nếu nội dung của văn bản là như thế này:

good baby 
bad boy 
good boy 
normal boy 

Tôi không muốn đầu ra để có những dòng sản phẩm nào. vì vậy không thích:

good baby 

good boy 
normal boy 

nhưng như thế này:

good baby 
good boy 
normal boy 

tôi nên chỉnh sửa gì từ mã của tôi trên trên?

+0

Tại sao bạn thay thế dấu chấm bằng dấu cách trong các dòng bạn muốn bỏ qua? – geoffspear

+0

@Wooble Có lẽ OP hy vọng rằng đó là một biểu thức chính quy, nơi anh ta sẽ 'thay thế' tất cả các lần xuất hiện của' bất cứ điều gì' trong 'dòng' bằng' không có gì'. – jadkik94

Trả lời

32

Bạn có thể làm cho mã của bạn đơn giản hơn và dễ đọc hơn như thế này

bad_words = ['bad', 'naughty'] 

with open('oldfile.txt') as oldfile, open('newfile.txt', 'w') as newfile: 
    for line in oldfile: 
     if not any(bad_word in line for bad_word in bad_words): 
      newfile.write(line) 

sử dụng một Context Managerany.

4

Bạn chỉ cần không bao gồm dòng vào tệp mới thay vì thay thế.

for line in infile : 
    if 'bad' not in line and 'naughty' not in line: 
      newopen.write(line) 
+1

tôi nghĩ rằng bạn muốn "hoặc" thay vì "và" –

+4

tôi nghĩ "và" là chính xác –

+0

tôi muốn các dòng chỉ chứa một trong số xấu hoặc không được xóa quá. cái nào là đúng..? –

1

else chỉ được kết nối với if mới nhất. Bạn muốn elif:

if 'bad' in line: 
    pass 
elif 'naughty' in line: 
    pass 
else: 
    newopen.write(line) 

Cũng lưu ý rằng tôi loại bỏ các dòng thay thế, như bạn không viết những dòng anyway.

0
to_skip = ("bad", "naughty") 
out_handle = open("testout", "w") 

with open("testin", "r") as handle: 
    for line in handle: 
     if set(line.split(" ")).intersection(to_skip): 
      continue 
     out_handle.write(line) 
out_handle.close() 
+0

Sẽ không hoạt động nếu có điều gì đó giống như 'điều này là xấu!' Trong tệp đầu vào. – sloth

0

Hôm nay tôi cần hoàn thành một nhiệm vụ tương tự vì vậy tôi đã viết một ý chính để hoàn thành nhiệm vụ dựa trên một số nghiên cứu tôi đã làm. Tôi hy vọng rằng ai đó sẽ thấy điều này hữu ích!

import os 

os.system('cls' if os.name == 'nt' else 'clear') 

oldfile = raw_input('{*} Enter the file (with extension) you would like to strip domains from: ') 
newfile = raw_input('{*} Enter the name of the file (with extension) you would like me to save: ') 

emailDomains = ['windstream.net', 'mail.com', 'google.com', 'web.de', 'email', 'yandex.ru', 'ymail', 'mail.eu', 'mail.bg', 'comcast.net', 'yahoo', 'Yahoo', 'gmail', 'Gmail', 'GMAIL', 'hotmail', 'comcast', 'bellsouth.net', 'verizon.net', 'att.net', 'roadrunner.com', 'charter.net', 'mail.ru', '@live', 'icloud', '@aol', 'facebook', 'outlook', 'myspace', 'rocketmail'] 

print "\n[*] This script will remove records that contain the following strings: \n\n", emailDomains 

raw_input("\n[!] Press any key to start...\n") 

linecounter = 0 

with open(oldfile) as oFile, open(newfile, 'w') as nFile: 
    for line in oFile: 
     if not any(domain in line for domain in emailDomains): 
      nFile.write(line) 
      linecounter = linecounter + 1 
      print '[*] - {%s} Writing verified record to %s ---{ %s' % (linecounter, newfile, line) 

print '[*] === COMPLETE === [*]' 
print '[*] %s was saved' % newfile 
print '[*] There are %s records in your saved file.' % linecounter 

Liên kết đến Gist: emailStripper.py

nhất, Az

0

Sử dụng python-textops gói:

from textops import * 

'oldfile.txt' | cat() | grepv('bad') | tofile('newfile.txt') 
0

Tôi đã sử dụng này để loại bỏ từ không mong muốn từ các tập tin văn bản:

bad_words = ['abc', 'def', 'ghi', 'jkl'] 

with open('List of words.txt') as badfile, open('Clean list of words.txt', 'w') as cleanfile: 
    for line in badfile: 
     clean = True 
     for word in bad_words: 
      if word in line: 
       clean = False 
     if clean == True: 
      cleanfile.write(line) 

Hoặc để làm tương tự cho tất cả các file trong một thư mục:

import os 

bad_words = ['abc', 'def', 'ghi', 'jkl'] 

for root, dirs, files in os.walk(".", topdown = True): 
    for file in files: 
     if '.txt' in file: 
      with open(file) as filename, open('clean '+file, 'w') as cleanfile: 
       for line in filename: 
        clean = True 
        for word in bad_words: 
         if word in line: 
          clean = False 
        if clean == True: 
         cleanfile.write(line) 

Tôi chắc rằng có phải là một cách thanh lịch hơn để làm điều đó, nhưng điều này đã làm những gì tôi muốn nó.

Các vấn đề liên quan