I need help converting this python code to c# could someone help me please?

#!/usr/bin/env python
# encoding: utf-8

import sys, getopt
import os, urllib, urllib2, re, string, math

help_message = '''
'''
no_param = '''
'''

verbose = False
fakeMode = False
curPath = os.getcwd() + "/"
# Should use Beautiful Soup to do this, but I'm not for ease of portability
nextRegex = '<a href="([^"]*)" class="next_page" rel="next">Next</a>'

urlRegex = ''
trackRegex = ''
outputPath = ''
currentSong = ''

class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

def removeDuplicates(seq):
    # Not order preserving
    keys = {}
    for e in seq:
        keys[e] = 1
    return keys.keys()

def go(artistname):
    print "Having a look at " + string.capwords(artistname)

    global urlRegex, trackRegex, outputPath, currentSong

    url = 'http://soundcloud.com/' + artistname # + '/tracks?page=3'

    urlRegex = '/'+artistname+'/.+/download'
    trackRegex = '/'+artistname+'/(.*?)/download'
    outputPath = curPath+artistname+"/"

    if not os.path.exists(outputPath):
        os.makedirs(outputPath)

    songlist = []

    while(len(url)):
        # loops for as long as there is a next page
        newlist, url = scrapePage(url, artistname)
        songlist.extend(newlist)

    print 'Found %s songs.' % len(songlist)

    for song in songlist:
        mp3url = song['url']
        name = song['name']
        currentSong = name
        #print 'Downloading '+name,
        if not fakeMode:
            #print ''
            urllib.urlretrieve('http://soundcloud.com' + mp3url, outputPath+name)
        else:
            print 'Not downloading %s.' % name
    print "All done with %s!" % artistname

def scrapePage(url, artistname):
    print 'Looking through '+url
    html = urllib2.urlopen(url).read()
    mp3list = re.findall(urlRegex, html)
    mp3list = removeDuplicates(mp3list)

    songs = []

    for mp3url in mp3list:
        r = re.compile(trackRegex)
        trackname = r.search(mp3url).group(1)
        trackname = trackname.replace('-', ' ')
        name = artistname + " - " + trackname + ".mp3"
        name = string.capwords(name)
        songs.append({'name':name,'url':mp3url})

    r = re.compile(nextRegex)
    result = r.search(html)
    if result:
        nextUrl = 'http://soundcloud.com' + result.group(1)
    else:
        nextUrl = ''

    return songs, nextUrl


def main(argv=None):
    global verbose, fakeMode

    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "ho:vf", ["help", "output="])
        except getopt.error, msg:
            raise Usage(msg)

        # option processing
        for option, value in opts:
            if option == "-v":
                verbose = True
            if option in ("-f", "--fake"):
                fakeMode = True
            if option in ("-h", "--help"):
                raise Usage(help_message)
            if option in ("-o", "--output"):
                output = value

        if len(args):
            artists = args
        else:
            raise Usage(no_param)

    except Usage, err:
        print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
        if err.msg != help_message:
            print >> sys.stderr, "\t for help use --help"
        return 2

    for artist in artists:
        go(artist)


if __name__ == "__main__":
    sys.exit(main())

Recommended Answers

All 7 Replies

At a glance it doesn't seem like the Python code uses anything that's terribly difficult in C#. What parts are you having trouble with? Do you know both Python and C#?

I don't know much python i got this from the internet and i would like to copy it and translate it to c# but i can't seem to work it out.

Sounds like a good time to learn a little Python. :) No offense, but even though the program is short, I'm not sure anyone will be willing to do the conversion for you. If you have specific questions like which libraries correspond to each other between languages or specific problems/errors you're seeing, that's fine.

The bear will be in the import modules

The bear will be in the import modules

Nah, they're all pretty universal as far as features go. C# (.NET rather, and probably Mono) support all of them in some form or another.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.