def match_text[raw_data_file, concentration]:
file = open[raw_data_file, 'r']
lines = ""
print["Testing"]
for num, line in enumerate[file.readlines[], 0]:
w = ' WITH A CONCENTRATION IN ' + concentration
if re.search[w, line]:
for i in range[0, 6]:
lines += linecache.getline[raw_data_file, num+1]
try:
write[lines, "lines.txt"]
print["Lines Data Created..."]
except:
print["Could not print Line Data"]
else:
print["Didn't Work"]
Tôi đang cố gắng mở một tệp .txt và tìm kiếm một chuỗi cụ thể.
Chuck
8566 Huy hiệu bạc17 Huy hiệu đồng6 silver badges17 bronze badges
Đã hỏi ngày 14 tháng 3 năm 2016 lúc 5:05Mar 14, 2016 at 5:05
5
Nếu bạn chỉ đơn giản là cố gắng viết tất cả các dòng giữ chuỗi của bạn vào một tệp, điều này sẽ làm.
def match_text[raw_data_file, concentration]:
look_for = ' WITH A CONCENTRATION IN ' + concentration
with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout:
fout.writelines[line for line in fin if look_for in line]
Đã trả lời ngày 14 tháng 3 năm 2016 lúc 5:27Mar 14, 2016 at 5:27
tdelaneytdelaneytdelaney
67.5K5 Huy hiệu vàng74 Huy hiệu bạc106 Huy hiệu đồng5 gold badges74 silver badges106 bronze badges
1
Đã khắc phục vấn đề của riêng tôi. Các hoạt động sau đây để tìm một dòng cụ thể và nhận các dòng theo dòng phù hợp.
def match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text
Điều này sẽ trả về nhiều dòng cộng với chuỗi phù hợp mà người dùng muốn. Tôi xin lỗi nếu câu hỏi thật khó hiểu.
Đã trả lời ngày 14 tháng 3 năm 2016 lúc 16:45Mar 14, 2016 at 16:45
M. Barbierim. BarbieriM. Barbieri
4722 Huy hiệu vàng13 Huy hiệu bạc26 Huy hiệu đồng2 gold badges13 silver badges26 bronze badges
Bài viết này cho bạn biết cách đọc một dòng cụ thể từ một tệp theo số dòng trong Python.
Chúng ta hãy giả sử tệp để đọc là lớn đáng kể [tính bằng GB] và bạn không muốn đọc toàn bộ tệp trong bộ nhớ cùng một lúc nhưng chỉ muốn nhảy và đọc dòng #5 và #120. Để đọc các dòng cụ thể từ tệp văn bản, vui lòng làm theo các bước sau:
- Mở tệp ở chế độ đọc
Để mở một tệp PASS PASS và chế độ truy cập
6 đến hàmdef match_text[raw_data_file, concentration]: look_for = ' WITH A CONCENTRATION IN ' + concentration with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout: fout.writelines[line for line in fin if look_for in line]
7. Chế độ truy cập chỉ định thao tác bạn muốn thực hiện trên tệp, chẳng hạn như đọc hoặc viết. Ví dụ,def match_text[raw_data_file, concentration]: look_for = ' WITH A CONCENTRATION IN ' + concentration with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout: fout.writelines[line for line in fin if look_for in line]
8 để đọc một tệp.def match_text[raw_data_file, concentration]: look_for = ' WITH A CONCENTRATION IN ' + concentration with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout: fout.writelines[line for line in fin if look_for in line]
For example,
8 to read a file.def match_text[raw_data_file, concentration]: look_for = ' WITH A CONCENTRATION IN ' + concentration with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout: fout.writelines[line for line in fin if look_for in line]
- Tạo danh sách để lưu trữ số dòng
Tạo một danh sách với số lượng của mỗi dòng trong một tệp văn bản để đọc. Ví dụ,
9. Ở đây chúng tôi đang đọc dòng 4 và 7.def match_text[raw_data_file, concentration]: look_for = ' WITH A CONCENTRATION IN ' + concentration with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout: fout.writelines[line for line in fin if look_for in line]
For example,
9. Here we are reading lines 4 and 7.def match_text[raw_data_file, concentration]: look_for = ' WITH A CONCENTRATION IN ' + concentration with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout: fout.writelines[line for line in fin if look_for in line]
- Tạo một danh sách để lưu trữ các dòng
Sau khi đọc dòng 4 và 7, chúng tôi sẽ lưu trữ kết quả trong một biến danh sách.
- Sử dụng cho vòng lặp với hàm Enumerate [] để có được một dòng và số của nó.
Hàm liệt kê [] thêm một bộ đếm cho một điều khác nhau và trả về nó trong việc liệt kê đối tượng. Chuyển các con trỏ tệp được trả về bởi hàm
7 chodef match_text[raw_data_file, concentration]: look_for = ' WITH A CONCENTRATION IN ' + concentration with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout: fout.writelines[line for line in fin if look_for in line]
def match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text
1. Chúng ta có thể sử dụng đối tượng liệt kê này với một vòng lặp để truy cập số dòng.note:def match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text
2 không tải toàn bộ tệp trong bộ nhớ, vì vậy đây là một giải pháp hiệu quả.
We can use this enumerate object with a for loop to access the line number.
Note:def match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text
2 doesn’t load the entire file in memory, so this is an efficient solution. - Đọc tệp theo số
Sử dụng điều kiện IF trong mỗi lần lặp của một vòng để kiểm tra số dòng. Nếu nó phù hợp, thì hãy lưu dòng đó vào một danh sách.
Ví dụ: Đọc các dòng cụ thể từ tệp theo số
Mã sau đây hiển thị & nbsp; Cách đọc tệp văn bản theo số dòng trong Python. Xem tệp đính kèm được sử dụng trong ví dụ và hình ảnh để hiển thị nội dung tệp để tham khảo.how to read a text file by line number in Python. See the attached file used in the example and an image to show the file’s content for reference.
Trong ví dụ này, chúng tôi đang đọc dòng số 4 và 7 và lưu trữ nó trong một biến danh sách.reading line number 4 and 7 and storing it in a list variable.
with open[r"E:\demos\files\read_demo.txt", 'r'] as fp:
# lines to read
line_numbers = [4, 7]
# To store lines
lines = []
for i, line in enumerate[fp]:
# read line 4 and 7
if i in line_numbers:
lines.append[line.strip[]]
elif i > 7:
# don't read after line 7 to save time
break
print[lines]
Output::
['Fifth line', 'Eighth Line']
Mô -đun linecache đọc dòng từ một tệp theo số dòng
Trong phần này, chúng tôi sẽ thấy cách đọc tệp theo số dòng bằng mô -đun linecache.
Python sườn linecache là một cách được tối ưu hóa hiệu suất khác để nhảy vào một dòng cụ thể trong một tệp văn bản. Giả sử nếu bạn có một tệp văn bản lớn, thì LineCache là lựa chọn chính xác.jump to a particular line in a text file. Assume if you have a large text file, then linecache is the correct choice.
Mô -đun linecache cho phép một dòng nhận bất kỳ dòng nào từ tệp nguồn Python, trong khi cố gắng tối ưu hóa nội bộ, sử dụng bộ đệm, trường hợp phổ biến trong đó nhiều dòng được đọc từ một tệp. Điều này được sử dụng bởi mô -đun Traceback để truy xuất các dòng nguồn để đưa vào dấu vết được định dạng.
Tài liệu Python
Sử dụng phương thức def match_text[raw_data_file, match_this_text]:
w = match_this_text
lines = ""
with open[raw_data_file, 'r'] as inF:
for line in inF:
if w in line:
lines += line //Will add the matched text to the lines string
for i in range[0, however_many_lines_after_matched_text]:
lines += next[inF]
//do something with 'lines', which is final multiline text
3 để đọc dòng cụ thể từ một tệp.the
def match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text3 method to read specific line from a file.
linecache.getline[filename, lineno, module_globals=None]
- Nhận dòng
def match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text
4 từ một tệp có têndef match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text
5. Hàm này sẽ không trả về bất kỳ lỗi nào nếu dòng không có trong một tệp thay thế, nó sẽ trả về một chuỗi trống. - Thay đổi
def match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text
4 thành số dòng mong muốn của bạn và bạn đã sẵn sàng để đi.
Thí dụ
import linecache
# read fifth line
line = linecache.getline[r"E:\demos\files\read_demo.txt", 5]
print[line]
Output::
Fifth line
Lưu ý: Linache đọc toàn bộ tệp trong bộ nhớ. Vì vậy, nếu quyền truy cập ngẫu nhiên vào số dòng quan trọng hơn hiệu suất, thì hãy sử dụng Linache.: The linache reads the whole file in memory. So, if random access to line number is more important than performance, then use linache.
Nếu bạn muốn đọc nhiều hơn một số dòng từ một tệp sử dụng linecache, hãy sử dụng ví dụ dưới đây.
import linecache
line_numbers = [2, 4]
lines = []
for i in line_numbers:
x = linecache.getline[r"E:\demos\files\read_demo.txt", i].strip[]
lines.append[x]
print[lines]
Sử dụng def match_text[raw_data_file, match_this_text]:
w = match_this_text
lines = ""
with open[raw_data_file, 'r'] as inF:
for line in inF:
if w in line:
lines += line //Will add the matched text to the lines string
for i in range[0, however_many_lines_after_matched_text]:
lines += next[inF]
//do something with 'lines', which is final multiline text
7 để đọc phạm vi dòng từ tệp
Nếu kích thước tệp của bạn nhỏ và bạn không quan tâm đến hiệu suất, thì phương thức readlines [] phù hợp nhất.
Đọc một tệp trong Python rất nhanh nếu kích thước tệp có trong vài MB.
Phương thức
def match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text7 đọc tất cả các dòng từ một tệp và lưu trữ nó trong danh sách. Bạn có thể sử dụng một số chỉ mục làm số dòng để trích xuất một tập hợp các dòng từ nó.
def match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text7 method reads all lines from a file and stores it in a list. You can use an index number as a line number to extract a set of lines from it.
Đây là cách đơn giản nhất để đọc một dòng cụ thể từ một tệp trong Python. Chúng tôi đọc toàn bộ tệp bằng cách sử dụng theo cách này và sau đó chọn các dòng cụ thể từ nó theo yêu cầu của chúng tôi.
Sử dụng
def match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text9 để đọc phạm vi của các dòng.
- Bắt đầu là số dòng đầu tiên
- Kết thúc là số dòng cuối cùng
- Để đọc từ dòng số 3 đến 5 sử dụng
0with open[r"E:\demos\files\read_demo.txt", 'r'] as fp: # lines to read line_numbers = [4, 7] # To store lines lines = [] for i, line in enumerate[fp]: # read line 4 and 7 if i in line_numbers: lines.append[line.strip[]] elif i > 7: # don't read after line 7 to save time break print[lines]
- Để đọc một dòng duy nhất sử dụng
1. Điều này sẽ đọc dòng thứ ba.with open[r"E:\demos\files\read_demo.txt", 'r'] as fp: # lines to read line_numbers = [4, 7] # To store lines lines = [] for i, line in enumerate[fp]: # read line 4 and 7 if i in line_numbers: lines.append[line.strip[]] elif i > 7: # don't read after line 7 to save time break print[lines]
Ví dụ: Đọc dòng từ 3 đến 5: Read line from 3 to 5
with open[r"E:\demos\files\read_demo.txt", 'r'] as fp:
# read line number 3 to 5
# index starts from 0
x = fp.readlines[][2:5]
print[x]
Ví dụ: Đọc dòng 8: Read line 8
def match_text[raw_data_file, concentration]:
look_for = ' WITH A CONCENTRATION IN ' + concentration
with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout:
fout.writelines[line for line in fin if look_for in line]
0Bạn cũng có thể sử dụng phương thức
with open[r"E:\demos\files\read_demo.txt", 'r'] as fp:
# lines to read
line_numbers = [4, 7]
# To store lines
lines = []
for i, line in enumerate[fp]:
# read line 4 and 7
if i in line_numbers:
lines.append[line.strip[]]
elif i > 7:
# don't read after line 7 to save time
break
print[lines]
2 để đọc từng dòng tệp, dừng lại khi bạn đã đến các dòng bạn muốn. Sử dụng kỹ thuật này, chúng tôi không cần phải đọc toàn bộ tập tin.read a file line by line, stop when you’ve gotten to the lines you want. Using this technique, we don’t need to read the entire file.Ví dụ 3:
def match_text[raw_data_file, concentration]:
look_for = ' WITH A CONCENTRATION IN ' + concentration
with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout:
fout.writelines[line for line in fin if look_for in line]
1Trình tạo để đọc các dòng từ một tệp theo số dòng
Một giải pháp nhanh và nhỏ gọn có thể là một biểu thức máy phát để đọc một tệp bằng số dòng.
Nếu số lượng dòng được trả về từ một tệp lớn, bạn nên sử dụng trình tạo., you should use the generator.
Giải pháp này chấp nhận con trỏ tệp và số dòng sẽ được đọc trả về một đối tượng Trình tạo để lặp lại bằng một vòng lặp để có được mỗi dòng.
def match_text[raw_data_file, concentration]:
look_for = ' WITH A CONCENTRATION IN ' + concentration
with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout:
fout.writelines[line for line in fin if look_for in line]
2Output::
def match_text[raw_data_file, concentration]:
look_for = ' WITH A CONCENTRATION IN ' + concentration
with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout:
fout.writelines[line for line in fin if look_for in line]
3cho vòng lặp trong with open[r"E:\demos\files\read_demo.txt", 'r'] as fp:
# lines to read
line_numbers = [4, 7]
# To store lines
lines = []
for i, line in enumerate[fp]:
# read line 4 and 7
if i in line_numbers:
lines.append[line.strip[]]
elif i > 7:
# don't read after line 7 to save time
break
print[lines]
3 để đọc các dòng cụ thể trong Python
with open[r"E:\demos\files\read_demo.txt", 'r'] as fp:
# lines to read
line_numbers = [4, 7]
# To store lines
lines = []
for i, line in enumerate[fp]:
# read line 4 and 7
if i in line_numbers:
lines.append[line.strip[]]
elif i > 7:
# don't read after line 7 to save time
break
print[lines]
Nếu kích thước tệp của bạn nhỏ và bạn không quan tâm đến hiệu suất, thì hãy sử dụng kỹ thuật lặp. and you are not concerned with performance, then use looping technique.
- Sử dụng cho vòng lặp để lặp từng dòng từ một đối tượng tệp
- Sử dụng điều kiện IF trong mỗi lần lặp của một vòng để kiểm tra số dòng. Nếu nó phù hợp, thì hãy lưu dòng đó vào một danh sách.
Lưu ý: Điều này sẽ tải toàn bộ tệp trong bộ nhớ.: This will load entire file in memory.
Example::
def match_text[raw_data_file, concentration]:
look_for = ' WITH A CONCENTRATION IN ' + concentration
with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout:
fout.writelines[line for line in fin if look_for in line]
4Output::
def match_text[raw_data_file, concentration]:
look_for = ' WITH A CONCENTRATION IN ' + concentration
with open[raw_data_file] as fin, open['lines.txt', 'w'] as fout:
fout.writelines[line for line in fin if look_for in line]
5Sự kết luận
- Sử dụng
4 hoặcwith open[r"E:\demos\files\read_demo.txt", 'r'] as fp: # lines to read line_numbers = [4, 7] # To store lines lines = [] for i, line in enumerate[fp]: # read line 4 and 7 if i in line_numbers: lines.append[line.strip[]] elif i > 7: # don't read after line 7 to save time break print[lines]
2 và lặp vào các dòng lặp từ một đối tượng tệp nếu kích thước tệp nhỏ.size is small.with open[r"E:\demos\files\read_demo.txt", 'r'] as fp: # lines to read line_numbers = [4, 7] # To store lines lines = [] for i, line in enumerate[fp]: # read line 4 and 7 if i in line_numbers: lines.append[line.strip[]] elif i > 7: # don't read after line 7 to save time break print[lines]
- Sử dụng linecache cho một giải pháp sạch hơn. Thật nhanh nếu bạn đang đọc nhiều lần hoặc đọc các dòng khác nhau từ nhiều tệp.
- Sử dụng một vòng lặp và
def match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text
1 cho các tệp lớn vì chúng tôi không cần phải tải toàn bộ tệp trong bộ nhớ.def match_text[raw_data_file, match_this_text]: w = match_this_text lines = "" with open[raw_data_file, 'r'] as inF: for line in inF: if w in line: lines += line //Will add the matched text to the lines string for i in range[0, however_many_lines_after_matched_text]: lines += next[inF] //do something with 'lines', which is final multiline text
1 for large files because we don’t need to load the entire file in memory.
Bài tập và câu đố Python
Các bài tập mã hóa miễn phí và các câu đố bao gồm các vấn đề cơ bản của Python, cấu trúc dữ liệu, phân tích dữ liệu, v.v.
- Hơn 15 bài tập và câu đố dành riêng cho chủ đềTopic-specific Exercises and Quizzes
- Mỗi bài tập chứa 10 câu hỏi
- Mỗi bài kiểm tra chứa 12-15 mcq