Monday 19 January 2015

Read news from network news group using python


This lesson consists of a program to demonstrate how to read network news group using python. Here we are going to use a comp language python news group, how to pick an article from that news group and read it.

So here is a python script to do this operation.

# import function from nntplib (network news transfer protocol library) library.
from nntplib import *
# Create a server with NNTP from url which stores network news.
server = NNTP('news.aioe.org') 
#Connect to the server and return five different element that are going to be returned
#  resp -> response send after we made a connection to the server
# count -> the number of news article that has been retrieved.
# first -> number of the first article.
# last-> the number of the last article.
# name -> name of the returned articles.
(resp, count, first, last, name) = server.group('comp.lang.python')
#After receiving the above we need to return the list of subject from the server using a function 
# called  xhdr which is used to return a range of subject from the news group.
# 'subject we are interested in and first - last is the range, converting to string and concatenating with 
# a dash (-)
(resp, subjects) = server.xhdr('subject', (str(first) + '-' + str(last))) # i.e. '1-10'
#  Now we will list the subject with a for loop, here we are retrieving all subjects, but you can also 
# specify range of subjects to be retrieve say subjects[-15:]
for subject in subjects[-15:]:
    print(subject)

#Now prompt the user which article he wants to read
n = int(input('Enter number of the article you want to read : '))
#Retrieve the body of the article using a function called body. Convert the number to a string when 
# sending value to body.Data will be stored in the list below (reply, num....)

(reply, num, id, list) = server.body(str(n))
#So now we are going to read the content of the body stored in list
for line in list
  print(line)
 

# End of program..

Output of the program after execution


No comments: