Hướng dẫn python csv remove newline - python csv loại bỏ dòng mới

Bạn đang sửa tệp CSV, vì chúng có sai SV_a5d15EwfI8Zk1Zr;QID4;"<span style=""font-size:16px;""><strong>HOUR</strong> Interview completed at:</span>";HOUR;TE;SL;;;true;ValidNumber;0;23.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID6;"<span style=""font-size:16px;""><strong>MINUTE</strong> Interview completed:</span>";MIN;TE;SL;;;true;ValidNumber;0;59.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID8;Number of Refusals - no language<br />For <strong>Zero Refusals - no language</strong> use 0;REFUSAL1;TE;SL;;;true;ValidNumber;0;99.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID10;<strong>DAY OF WEEK:</strong>;WEEKDAY;MC;SACOL;TX;;true;;0;;;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID45;"<span style=""font-size:16px;"">Using points from 0 to 10, how likely would you be recommend Gatwick Airport to a friend or colleague?</span><div> </div>";NPSCORE;MC;NPS;;;true;;0;;;882;-873; 5 Vấn đề ở đây là làm thế nào để biết dòng có phải là một phần của dòng trước đó hay không. Nếu tất cả các dòng bắt đầu bằng các từ cụ thể như trong ví dụ của bạn SV_a5d15EwfI8Zk1Zr;QID4;"<span style=""font-size:16px;""><strong>HOUR</strong> Interview completed at:</span>";HOUR;TE;SL;;;true;ValidNumber;0;23.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID6;"<span style=""font-size:16px;""><strong>MINUTE</strong> Interview completed:</span>";MIN;TE;SL;;;true;ValidNumber;0;59.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID8;Number of Refusals - no language<br />For <strong>Zero Refusals - no language</strong> use 0;REFUSAL1;TE;SL;;;true;ValidNumber;0;99.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID10;<strong>DAY OF WEEK:</strong>;WEEKDAY;MC;SACOL;TX;;true;;0;;;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID45;"<span style=""font-size:16px;"">Using points from 0 to 10, how likely would you be recommend Gatwick Airport to a friend or colleague?</span><div> </div>";NPSCORE;MC;NPS;;;true;;0;;;882;-873; 6 hoặc chỉ SV_a5d15EwfI8Zk1Zr;QID4;"<span style=""font-size:16px;""><strong>HOUR</strong> Interview completed at:</span>";HOUR;TE;SL;;;true;ValidNumber;0;23.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID6;"<span style=""font-size:16px;""><strong>MINUTE</strong> Interview completed:</span>";MIN;TE;SL;;;true;ValidNumber;0;59.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID8;Number of Refusals - no language<br />For <strong>Zero Refusals - no language</strong> use 0;REFUSAL1;TE;SL;;;true;ValidNumber;0;99.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID10;<strong>DAY OF WEEK:</strong>;WEEKDAY;MC;SACOL;TX;;true;;0;;;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID45;"<span style=""font-size:16px;"">Using points from 0 to 10, how likely would you be recommend Gatwick Airport to a friend or colleague?</span><div> </div>";NPSCORE;MC;NPS;;;true;;0;;;882;-873; 7, bạn có thể làm điều gì đó như thế này:

import glob # this is the FIX PART # I have file ./data.csv(contains your example) Fixed version is in data.csv.FIXED file_read_path = "./*.csv" for filename in glob.glob(file_read_path): with open(filename, "r", encoding='ISO-8859-1') as file, open(filename + '.FIXED', "w", encoding='ISO-8859-1') as target: previous_line = '' for line in file: # check if it's a new line or a part of the previous line if line.startswith('SV_'): if previous_line: target.write( previous_line + '\n') previous_line = line[:-1] # remove \n else: # concatenate the broken part with previous_line previous_line += line[:-1] # remove \n # add last line target.write(previous_line + '\n')

Ouput:

SV_a5d15EwfI8Zk1Zr;QID4;"<span style=""font-size:16px;""><strong>HOUR</strong> Interview completed at:</span>";HOUR;TE;SL;;;true;ValidNumber;0;23.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID6;"<span style=""font-size:16px;""><strong>MINUTE</strong> Interview completed:</span>";MIN;TE;SL;;;true;ValidNumber;0;59.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID8;Number of Refusals - no language<br />For <strong>Zero Refusals - no language</strong> use 0;REFUSAL1;TE;SL;;;true;ValidNumber;0;99.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID10;<strong>DAY OF WEEK:</strong>;WEEKDAY;MC;SACOL;TX;;true;;0;;;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID45;"<span style=""font-size:16px;"">Using points from 0 to 10, how likely would you be recommend Gatwick Airport to a friend or colleague?</span><div> </div>";NPSCORE;MC;NPS;;;true;;0;;;882;-873;

EDITS:

Có thể đơn giản hơn khi sử dụng SV_a5d15EwfI8Zk1Zr;QID4;"<span style=""font-size:16px;""><strong>HOUR</strong> Interview completed at:</span>";HOUR;TE;SL;;;true;ValidNumber;0;23.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID6;"<span style=""font-size:16px;""><strong>MINUTE</strong> Interview completed:</span>";MIN;TE;SL;;;true;ValidNumber;0;59.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID8;Number of Refusals - no language<br />For <strong>Zero Refusals - no language</strong> use 0;REFUSAL1;TE;SL;;;true;ValidNumber;0;99.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID10;<strong>DAY OF WEEK:</strong>;WEEKDAY;MC;SACOL;TX;;true;;0;;;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID45;"<span style=""font-size:16px;"">Using points from 0 to 10, how likely would you be recommend Gatwick Airport to a friend or colleague?</span><div> </div>";NPSCORE;MC;NPS;;;true;;0;;;882;-873; 8, điều này sẽ khắc phục tệp mà nó tự:

import glob # this is the FIX PART # I have file //data.csv the fixed version in the same file file_read_path = "./*.csv" # assuming that all lines starts with SV_ STARTING_KEYWORD = 'SV_' for filename in glob.glob(file_read_path): with open(filename, "r", encoding='ISO-8859-1') as file: lines = file.read().split(STARTING_KEYWORD) with open(filename, 'w', encoding='ISO-8859-1') as file: file.write('\n'.join(STARTING_KEYWORD + l.replace('\n', '') for l in lines if l))

Dưới đây là nhiều tối ưu hóa và ứng dụng của phong cách Python thích hợp để làm cho mã của bạn gọn gàng hơn rất nhiều. Tôi đã đặt một số mã tùy chọn bằng mô -đun SV_a5d15EwfI8Zk1Zr;QID4;"<span style=""font-size:16px;""><strong>HOUR</strong> Interview completed at:</span>";HOUR;TE;SL;;;true;ValidNumber;0;23.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID6;"<span style=""font-size:16px;""><strong>MINUTE</strong> Interview completed:</span>";MIN;TE;SL;;;true;ValidNumber;0;59.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID8;Number of Refusals - no language<br />For <strong>Zero Refusals - no language</strong> use 0;REFUSAL1;TE;SL;;;true;ValidNumber;0;99.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID10;<strong>DAY OF WEEK:</strong>;WEEKDAY;MC;SACOL;TX;;true;;0;;;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID45;"<span style=""font-size:16px;"">Using points from 0 to 10, how likely would you be recommend Gatwick Airport to a friend or colleague?</span><div> </div>";NPSCORE;MC;NPS;;;true;;0;;;882;-873; 9, mong muốn hơn so với phân tích thủ công. Tôi cũng đã đặt một chút tốt đẹp ____20, nhưng tôi không sử dụng các thuộc tính mà sau đó cung cấp. Tên của các phần của tên gọi là không chính xác, bạn sẽ cần sửa chúng.

Nội phân chính

  • Phương thức số 1: Xóa dòng mới khỏi tệp bằng cách sử dụng thay thế ()
  • Phương thức #2: & nbsp; Xóa các dòng mới khỏi tệp bằng splutlines ()
  • Phương pháp #3: & nbsp; Xóa các dòng mới khỏi tệp bằng Regex
  • Làm thế nào để bạn xóa Newline khỏi tệp văn bản trong Python?
  • '\ N làm gì trong Python?
  • Dải () loại bỏ \ n?
  • Làm cách nào để loại bỏ ký tự dòng mới trong một tệp văn bản?

import csv from collections import namedtuple from time import localtime, strftime # Method one, reading the file into lists manually (less desirable) with open('grades.dat') as files: grades = [[e.strip() for e in s.split(',')] for s in files] # Method two, using csv and namedtuple StudentRecord = namedtuple('StudentRecord', 'id, lastname, firstname, something, homework1, homework2, homework3, homework4, homework5, homework6, homework7, exam1, exam2, exam3') grades = map(StudentRecord._make, csv.reader(open('grades.dat'))) # Now you could have student.id, student.lastname, etc. # Skipping the namedtuple, you could do grades = map(tuple, csv.reader(open('grades.dat'))) request = open('requests.dat', 'w') cont = 'y' while cont.lower() == 'y': answer = raw_input('Please enter the Student I.D. of whom you are looking: ') for student in grades: if answer == student[0]: print '%s, %s %s %s' % (student[1], student[2], student[0], student[3]) time = strftime('%a, %b %d %Y %H:%M:%S', localtime()) print time print 'Exams - %s, %s, %s' % student[11:14] print 'Homework - %s, %s, %s, %s, %s, %s, %s' % student[4:11] total = sum(int(x) for x in student[4:14]) print 'Total points earned - %d' % total grade = total / 5.5 if grade >= 90: letter = 'an A' elif grade >= 80: letter = 'a B' elif grade >= 70: letter = 'a C' elif grade >= 60: letter = 'a D' else: letter = 'an F' if letter = 'an A': print 'Grade: %s, that is equal to %s.' % (grade, letter) else: print 'Grade: %.2f, that is equal to %s.' % (grade, letter) request.write('%s %s, %s %s\n' % (student[0], student[1], student[2], time)) print cont = raw_input('Would you like to search again? ') print 'Goodbye.'
  • Mở TextPad và tệp bạn muốn chỉnh sửa. Nhấp vào Tìm kiếm và sau đó thay thế. Trong cửa sổ thay thế, trong phần tìm phần nào, gõ ^\ n (Caret, Backslash 'n') và để trống thay thế, trừ khi bạn muốn thay thế một dòng trống bằng văn bản khác. Kiểm tra hộp biểu thức thông thường.
  • Dưới đây là nhiều tối ưu hóa và ứng dụng của phong cách Python thích hợp để làm cho mã của bạn gọn gàng hơn rất nhiều. Tôi đã đặt một số mã tùy chọn bằng mô -đun SV_a5d15EwfI8Zk1Zr;QID4;"<span style=""font-size:16px;""><strong>HOUR</strong> Interview completed at:</span>";HOUR;TE;SL;;;true;ValidNumber;0;23.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID6;"<span style=""font-size:16px;""><strong>MINUTE</strong> Interview completed:</span>";MIN;TE;SL;;;true;ValidNumber;0;59.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID8;Number of Refusals - no language<br />For <strong>Zero Refusals - no language</strong> use 0;REFUSAL1;TE;SL;;;true;ValidNumber;0;99.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID10;<strong>DAY OF WEEK:</strong>;WEEKDAY;MC;SACOL;TX;;true;;0;;;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID45;"<span style=""font-size:16px;"">Using points from 0 to 10, how likely would you be recommend Gatwick Airport to a friend or colleague?</span><div> </div>";NPSCORE;MC;NPS;;;true;;0;;;882;-873; 9, mong muốn hơn so với phân tích thủ công. Tôi cũng đã đặt một chút tốt đẹp ____20, nhưng tôi không sử dụng các thuộc tính mà sau đó cung cấp. Tên của các phần của tên gọi là không chính xác, bạn sẽ cần sửa chúng.

Nội phân chính'\n' character represents the new line in python programming. However, this tutorial will show you various methods to remove the newlines from a text file.

Phương thức số 1: Xóa dòng mới khỏi tệp bằng cách sử dụng thay thế ()

# Open the file my_file = open('my_file.txt', 'r') # Read my_file with newlines character output = repr(my_file.read()) # Output print(output) # Close the file my_file.close()

Output:

'\nHello World\nHello Python\nHello Javascript\n

Phương thức #2: & nbsp; Xóa các dòng mới khỏi tệp bằng splutlines (): I've used the repr() function to print the file's output with the '\n' character.

Phương pháp #3: & nbsp; Xóa các dòng mới khỏi tệp bằng Regex

Phương thức số 1: Xóa dòng mới khỏi tệp bằng cách sử dụng thay thế ()

Phương thức #2: & nbsp; Xóa các dòng mới khỏi tệp bằng splutlines ()replace() method replaces a specified phrase with another specified phrase. Therefore, we'll use this method to replace the newline character with a non-value.

Cú pháp

.replace('\n', '')

Thí dụ

# Open the file my_file = open('my_file.txt', 'r') # File's output o = my_file.read() # Remove all new lines from file r_newlines = o.replace('\n', '') # Result print(r_newlines) # Close the file my_file.close()

Output:

Hello WorldHello PythonHello Javascript

Phương thức #2: & nbsp; Xóa các dòng mới khỏi tệp bằng splutlines ()

Phương pháp #3: & nbsp; Xóa các dòng mới khỏi tệp bằng Regexsplitlines() method splits a string at the newline break and returns the result as a list.

Py py'\n' and the join() method to join the result.

Cú pháp

Ngày 28 tháng 12 năm 2021

Thí dụ

SV_a5d15EwfI8Zk1Zr;QID4;"<span style=""font-size:16px;""><strong>HOUR</strong> Interview completed at:</span>";HOUR;TE;SL;;;true;ValidNumber;0;23.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID6;"<span style=""font-size:16px;""><strong>MINUTE</strong> Interview completed:</span>";MIN;TE;SL;;;true;ValidNumber;0;59.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID8;Number of Refusals - no language<br />For <strong>Zero Refusals - no language</strong> use 0;REFUSAL1;TE;SL;;;true;ValidNumber;0;99.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID10;<strong>DAY OF WEEK:</strong>;WEEKDAY;MC;SACOL;TX;;true;;0;;;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID45;"<span style=""font-size:16px;"">Using points from 0 to 10, how likely would you be recommend Gatwick Airport to a friend or colleague?</span><div> </div>";NPSCORE;MC;NPS;;;true;;0;;;882;-873; 0

Output:

Hello WorldHello PythonHello Javascript

Phương pháp #3: & nbsp; Xóa các dòng mới khỏi tệp bằng Regex

Py pyre.sub() function to remove the newlines from a text file.

Cú pháp

SV_a5d15EwfI8Zk1Zr;QID4;"<span style=""font-size:16px;""><strong>HOUR</strong> Interview completed at:</span>";HOUR;TE;SL;;;true;ValidNumber;0;23.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID6;"<span style=""font-size:16px;""><strong>MINUTE</strong> Interview completed:</span>";MIN;TE;SL;;;true;ValidNumber;0;59.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID8;Number of Refusals - no language<br />For <strong>Zero Refusals - no language</strong> use 0;REFUSAL1;TE;SL;;;true;ValidNumber;0;99.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID10;<strong>DAY OF WEEK:</strong>;WEEKDAY;MC;SACOL;TX;;true;;0;;;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID45;"<span style=""font-size:16px;"">Using points from 0 to 10, how likely would you be recommend Gatwick Airport to a friend or colleague?</span><div> </div>";NPSCORE;MC;NPS;;;true;;0;;;882;-873; 2

Hàm sub () hoạt động như hàm thay thế ().replace() function.

Thí dụ

SV_a5d15EwfI8Zk1Zr;QID4;"<span style=""font-size:16px;""><strong>HOUR</strong> Interview completed at:</span>";HOUR;TE;SL;;;true;ValidNumber;0;23.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID6;"<span style=""font-size:16px;""><strong>MINUTE</strong> Interview completed:</span>";MIN;TE;SL;;;true;ValidNumber;0;59.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID8;Number of Refusals - no language<br />For <strong>Zero Refusals - no language</strong> use 0;REFUSAL1;TE;SL;;;true;ValidNumber;0;99.0;0.0;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID10;<strong>DAY OF WEEK:</strong>;WEEKDAY;MC;SACOL;TX;;true;;0;;;882;-873;0 SV_a5d15EwfI8Zk1Zr;QID45;"<span style=""font-size:16px;"">Using points from 0 to 10, how likely would you be recommend Gatwick Airport to a friend or colleague?</span><div> </div>";NPSCORE;MC;NPS;;;true;;0;;;882;-873; 3

Output:

Hello WorldHello PythonHello JavascriptAdvertisementsAdvertisements

Sự kết luận

Chúng tôi đã học các phương pháp khác nhau để loại bỏ các dòng mới khỏi tệp văn bản trong bài viết này. Hơn nữa, nếu bạn muốn loại bỏ các dòng mới từ đầu hoặc cuối tệp văn bản, bạn nên sử dụng các phương thức Dải () và Rstrip ().

Làm thế nào để bạn xóa Newline khỏi tệp văn bản trong Python?

Tệp Python I/O: Xóa các ký tự mới ra khỏi tệp..

Giải pháp mẫu:.

Mã python: def remove_newlines (fname): flist = open (fname) .ReadLines () return [s.rstrip ('\ n') cho s trong flist] in (remove_newlines ("test.txt")).

Flowchart:.

Trình chỉnh sửa mã Python: ....

Có một cách khác để giải quyết giải pháp này ?.

'\ N làm gì trong Python?

Nhân vật dòng mới trong Python là \ n. Nó được sử dụng để chỉ ra sự kết thúc của một dòng văn bản.to indicate the end of a line of text.

Dải () loại bỏ \ n?

Phương thức Dải () loại bỏ khoảng trắng theo mặc định, do đó không cần phải gọi nó với các tham số như '\ t' hoặc '\ n'. Tuy nhiên, các chuỗi trong Python là bất biến và không thể được sửa đổi, tức là dòng. Dải () cuộc gọi sẽ không thay đổi đối tượng dòng. Kết quả là một chuỗi mới được trả về bởi cuộc gọi., so there is no need to call it with parameters like '\t' or '\n'. However, strings in Python are immutable and can't be modified, i.e. the line. strip() call will not change the line object. The result is a new string which is returned by the call.

Làm cách nào để loại bỏ ký tự dòng mới trong một tệp văn bản?

Mở TextPad và tệp bạn muốn chỉnh sửa.Nhấp vào Tìm kiếm và sau đó thay thế.Trong cửa sổ thay thế, trong phần tìm phần nào, gõ ^\ n (Caret, Backslash 'n') và để trống thay thế, trừ khi bạn muốn thay thế một dòng trống bằng văn bản khác.Kiểm tra hộp biểu thức thông thường.

Chủ đề