簡體   English   中英

在python中獲取第n行字符串

[英]get nth line of string in python

如何在Python 3中獲得字符串的第n行? 例如

getline("line1\nline2\nline3",3)

有沒有辦法使用stdlib / builtin函數? 我更喜歡Python 3中的解決方案,但Python 2也沒問題。

請嘗試以下方法:

s = "line1\nline2\nline3"
print s.splitlines()[2]

功能性方法

>>> import StringIO
>>> from itertools import islice
>>> s = "line1\nline2\nline3"
>>> gen = StringIO.StringIO(s)
>>> print next(islice(gen, 2, 3))
line3

使用字符串緩沖區:

import io    
def getLine(data, line_no):
    buffer = io.StringIO(data)
    for i in range(line_no - 1):
        try:
            next(buffer)
        except StopIteration:
            return '' #Reached EOF

    try:
        return next(buffer)
    except StopIteration:
        return '' #Reached EOF

從評論中看起來好像這個字符串非常大。 如果有太多數據可以輕松適應內存,一種方法是逐行處理文件中的數據:

N = ...
with open('data.txt') as inf:
    for count, line in enumerate(inf, 1):
        if count == N: #search for the N'th line
            print line

使用enumerate()為你提供索引和你迭代的對象的值,你可以指定一個起始值,所以我使用1(而不是默認值0)

使用with的優點是,當您完成或遇到異常時,它會自動為您關閉文件。

比分割字符串更有效的解決方案是迭代字符,找到第N個位置和第(N-1)個'\\ n'出現的位置(考慮字符串開頭的邊緣情況) 。 第N行是這些位置之間的子串。

這是一個雜亂的代碼來演示它(行號為1索引):

def getLine(data, line_no):
    n = 0
    lastPos = -1
    for i in range(0, len(data) - 1):
        if data[i] == "\n":
            n = n + 1
            if n == line_no:
                return data[lastPos + 1:i]
            else:
                lastPos = i;



    if(n == line_no - 1):
        return data[lastPos + 1:]
    return "" # end of string

這也比一次構建一個字符串的解決方案更有效。

既然你提出了內存效率,那就更好了:

s = "line1\nline2\nline3"

# number of the line you want
line_number = 2

i = 0
line = ''
for c in s:
   if i > line_number:
     break
   else:
     if i == line_number-1 and c != '\n':
       line += c
     elif c == '\n':
       i += 1

寫入兩個函數以提高可讀性

    string = "foo\nbar\nbaz\nfubar\nsnafu\n"

    def iterlines(string):
      word = ""
      for letter in string:
        if letter == '\n':
          yield word
          word = ""
          continue
        word += letter

    def getline(string, line_number):
      for index, word in enumerate(iterlines(string),1):
        if index == line_number:
          #print(word)
          return word

    print(getline(string, 4))
`my_string.strip().split("\n")[-1]`

我的解決方案(有效和緊湊):

def getLine(data, line_no):
    index = -1
    for _ in range(line_no):index = data.index('\n',index+1)
    return data[index+1:data.index('\n',index+1)]

暫無
暫無

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

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