2016-12-11 10 views
6

मैं एक पाठ फ़ाइल ("name_data.txt") है निम्नलिखित सामग्री है कि प्रिंट करूं:कैसे मैं केवल हर 5 लाइन

name: Kelo 
family name: Lam 
location: Asia 
members: Kelo, Kiko, Jil 

name: Miko 
family name: Naiton 
location: Japan 
members: Miko,Kayati 

पाठ फ़ाइल एक ही पैटर्न (नाम, परिवार का नाम, स्थान, सदस्यों के साथ जा रहा रखता है)

मैं पहली पंक्ति मुद्रित करना चाहता हूं और फिर प्रत्येक 5 वीं पंक्ति मुद्रित करना चाहता हूं, इसलिए मैं शुरुआत में "नाम" के साथ केवल पंक्ति प्रिंट कर रहा हूं।

["Kelo","Miko"] 

अब तक, मैं मिल गया है (हालांकि, यह गलत है): मैं तो नाम

मैं चाहता हूँ की एक सूची है करने के लिए अपने उत्पादन होना चाहता हूँ

name_data= load_local_file('name_data.txt',ignore_header=False,delimiter='\t') 


def __init __(name_reader): 

    names=list() 
    count=0 
    name_line=5 
    line_number=0 

    for name in name_data: 

     if line_number<5: 

      line_number +=1 

     if line_number ==5: 

      names.append(line_number) 

उत्तर

1

यह मानते हुए कि name_data फ़ाइल की पंक्तियों की एक सूची है, तो आप एक साधारण वा

names = [] 
for i in range(1, len(name_data), 5): 
    names.append(name_data[i].split(":")[1].strip()) 
2

कर सकते हैं y यह इस प्रकार किया जाएगा करने के लिए:

with open('name_data.txt', 'r') as file: 

    index = 0 
    for line in file: 
     if index % 5 == 0: 
      print(line.split()[1]) 
     index += 1 
+0

हाय tom_1230, आपकी टिप्पणी के लिए धन्यवाद। मैंने प्रिंट करने की कोशिश की (लाइन) और आउटपुट एक ट्रेसबैक के रूप में वापस आया: वापसी codecs.ascii_decode (इनपुट, self.errors) [0] यूनिकोडडेकोड त्रुटि: 'ascii' कोडेक स्थिति 0 में बाइट 0xef को डीकोड नहीं कर सकता: सामान्य नहीं रेंज (128); तुम्हें पता है उसका मतलब क्या है? – Robbie

+0

कोड मेरे लिए पूरी तरह से काम करता है, शायद टेक्स्ट फ़ाइल एन्कोडिंग गड़बड़ है। एक नई .txt फ़ाइल बनाएं और आपके मूल प्रश्न में निर्दिष्ट इनपुट की प्रतिलिपि बनाएँ और देखें कि क्या यह काम करता है। –

+0

मैंने अपने उत्तर में कोड भी अपडेट किया, बस एहसास हुआ कि आप केवल नाम प्रिंट करना चाहते हैं, न कि पूरी लाइन। –

4

आप एक नंबर के खिलाफ linenumber modulo 5 की तुलना द्वारा हर पांचवें लाइन की पहचान कर सकते हैं। आपके मामले में यह 0 होना चाहिए क्योंकि आप पहली पंक्ति और 6 वें, 11 वें, ... (ध्यान दें कि पायथन इंडेक्स 0 के साथ शुरू होता है)

लाइन-संख्याओं के साथ-साथ सामग्री को पुन: सक्रिय करने के लिए फ़ाइल पर enumerate के साथ।

फिर स्ट्रिंग के name: भाग को त्यागने के लिए और बाद में आने के बाद, आप str.split() का उपयोग कर सकते हैं।

एक काम कर क्रियान्वयन ऐसा दिखाई दे सकता है:

# Create an empty list for the names 
names = [] 

# Opening the file with "with" makes sure it is automatically closed even 
# if the program encounters an Exception. 
with open('name_data.txt', 'r') as file: 
    for lineno, line in enumerate(file): 
     # The lineno modulo 5 is zero for the first line and every fifth line thereafter. 
     if lineno % 5 == 0: 
      # Make sure it really starts with "name" 
      if not line.startswith('name'): 
       raise ValueError('line did not start with "name".') 
      # Split the line by the ":" and keep only what is coming after it. 
      # Using `maxsplit=1` makes sure you don't run into trouble if the name 
      # contains ":" as well (may be unnecessary but better safe than sorry!) 
      name = line.split(':', 1)[1] 
      # Remove any remaining whitespaces around the name 
      name = name.strip() 
      # Save the name in the list of names 
      names.append(name) 

# print out the list of names 
print(names) 
की गणना करने के बजाय आप भी एक कदम तर्क के साथ itertools.islice इस्तेमाल कर सकते हैं

:

from itertools import islice 

with open('name_data.txt', 'r') as file: 
    for line in islice(file, None, None, 5): 
     ... # like above except for the "if lineno % 5 == 0:" line 

अपनी आवश्यकताओं आप विचार कर सकते हैं पर निर्भर करता है फ़ाइल को पूरी तरह से पार्स करने के लिए re मॉड्यूल:

import re 
# The regular expression 
group = re.compile(r"name: (.+)\nfamily name: (.+)\nlocation: (.+)\nmembers: (.+)\n", flags=re.MULTILINE) 
with open(filename, 'r') as file: 
    # Apply the regex to your file 
    all_data = re.findall(group, file) 
# To get the names you just need the first element in each group: 
firstnames = [item[0] for item in all_data] 

firstnames अपने उदाहरण के लिए ['Kelo', 'Miko'] हो सकता है और इसी तरह अगर आप [item[1] for item in all_data] तो का उपयोग आप अंतिम नाम मिलता है: ['Lam', 'Naiton']। नियमित अभिव्यक्ति का सफलतापूर्वक उपयोग करने के लिए आपको यह सुनिश्चित करना होगा कि यह वास्तव में आपके फ़ाइल लेआउट से मेल खाता है अन्यथा आपको गलत परिणाम मिलेंगे।

+1

आपका 'इस्लिस' समाधान अच्छा है ... – MaxU

2

आप इस प्रकार एक सूची समझ

c = open('test.txt', 'r').readlines() 

# for every fifth line extract out name and store in list 
a = [i.replace('name: ', '').replace('\n', '') for i in c[::5]] 

print(a) # ['Kelo', 'Miko'] 
0

डेटा के साथ एक name_data.txt फ़ाइल होने के साथ एक पंक्ति में ऐसा कर सकता है: 1 2 3 4 5 6 7 8 9 10

करने का तरीका यहां पहले और इसके बारे में हर 5 वीं पंक्ति मुद्रित कर सकते हैं :

content = [line.rstrip('\n') for line in open('name_data.txt')] 
names = [] 
limit = 4 
fp = open("name_data.txt") 
names.append(content[0]) 
for i, line in enumerate(fp): 
    if i == limit: 
     names.append(line) 
     limit += 5 
fp.close() 
print(names) 

चेकआउट http://shortcode.pro/code/read-txt-file-and-print-first-and-every-5th-line/

0

आप नियमित अभिव्यक्तियों का उपयोग कर सकते हैं - इसके लिए पाइथन का मॉड्यूल re है।

फिर साथ name_data.txt किया जा रहा है:

name: Kelo 
family name: Lam 
location: Asia 
members: Kelo, Kiko, Jil 

name: Miko 
family name: Naiton 
location: Japan 
members: Miko,Kayati 

नाम प्राप्त करना सरल है एक लाइनर:

import re 

def get_names(): 

    with open('name_data.txt', 'r') as f: 
     print(re.findall(r'^name:\s*(\w+)', f.read(), flags=re.MULTILINE)) 

if __name__ == '__main__': 

    get_names() 

नोट बहु ध्वज सेटिंग - जब सेटिंग वैश्विक है, regex भी लाइनों से मेल खाएंगे family name: ... के साथ। इंटरएक्टिव मोड here में रेगेक्स देखें।

संबंधित मुद्दे