当前位置: 首页>>代码示例>>Python>>正文


Python util.read_file函数代码示例

本文整理汇总了Python中util.read_file函数的典型用法代码示例。如果您正苦于以下问题:Python read_file函数的具体用法?Python read_file怎么用?Python read_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了read_file函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _complete_path

    def _complete_path(self, item):

        c = re.compile(r"(%s)_(\d+)\.(\w+)" %
                       ("|".join(self.SUPPORTED_METHODS)))

        url_path = UrlPath(get_url_path(item[0][len(self.api_dir):]))

        for current_file in sorted(item[2]):
            m = c.match(current_file)
            if m is None:
                continue
            method, status_code, format = m.groups()

            if method in url_path.resources:
                url_path.resources[method].files.append(
                    ResourceFormatFile(
                        status_code,
                        format,
                        read_file("%s/%s" % (item[0], current_file))))
            else:
                resource = self._create_resource(
                    item[0], method, url_path.path)

                resource.files.append(
                    ResourceFormatFile(
                        status_code,
                        format,
                        read_file("%s/%s" % (item[0], current_file))))

                # add resource to url_path
                url_path.resources[method] = resource

        return url_path
开发者ID:BlinkTunnel,项目名称:stomach-server,代码行数:33,代码来源:methodslisting.py

示例2: save_user_sim_matrix

def save_user_sim_matrix(topics):
  for i in range(60):
    topic_path = 'user_similarity/user_topic_sim/'+str(topics)+'_topics/'+str(i)+".pickle"
    tag_path = 'user_similarity/user_tag_sim/'+str(i)+".pickle"
    topic_i = util.read_file(topic_path)
    tag_i = util.read_file(tag_path)
    for t in topic_i:
      topic_i[t] = topic_i[t]*tag_i[t]
    path = 'user_similarity/user_sim/'+str(topics)+'_hybrid/'+str(i)+".pickle"
    util.write_file(topic_i,path)
开发者ID:Tracywangsw,项目名称:recommender,代码行数:10,代码来源:recommend.py

示例3: importData

def importData():
    # read data and split training data into training and validation sets
    data_train, labels_train = read_file('training')
        
    #assert len(data_train[0]) == len(labels_train[0])
    #assert len(data_train[200]) == len(labels_train[200])

    data_test, labels_test = read_file('test')
            
    #assert len(data_test[0]) == len(data_test[0])
    #assert len(data_test[200]) == len(data_test[200])
    
    return data_train, data_test, labels_train, labels_test
开发者ID:5idaidai,项目名称:cse250B-1,代码行数:13,代码来源:P2_run_on_data.py

示例4: _find_files

def _find_files(url, folder, cookie):
    """
    Recursively find all files in current page.
    :param url: A URL to given page.
    :param folder: A destination folder for this page.
    :param cookie: A cookie file used for downloading.
    :return: A list of files (URL, path) in current page.
    """
    files = []

    path = '{}/temp.html'.format(folder)
    util.download(url, path, cookie)

    page = util.read_file(path)
    util.remove(path)

    # recursively find all files in sub-folders
    pattern = r'<tr><td colspan="4"><a href="(.*?)">(.*?)</a>'
    for find in re.finditer(pattern, page, re.DOTALL):
        url = find.group(1)
        sub_folder = '{}/{}'.format(folder, find.group(2))
        files += _find_files(url, sub_folder, cookie)

    # find all files in this page
    pattern = r'<tr><td>(.*?)</td>.*?Embed.*?<a href="(.*?)\?.*?">Download</a>'
    for find in re.finditer(pattern, page, re.DOTALL):
        url = find.group(2)
        file_name = find.group(1)
        path = u'{}/{}'.format(folder, file_name)
        files.append((url, path))

    return files
开发者ID:kq2,项目名称:Ricin,代码行数:32,代码来源:assets.py

示例5: run_test

def run_test(self, name, path, num_cores, args=[]):
    """ 
    Run a single test.
    """
    try:

        # Compile the program
        (exit, output) = call([COMPILE, path+'/'+name+'.sire'] 
                + ['-t', 'mpi', '-n', '{}'.format(num_cores)] + args)
        self.assertTrue(exit)

        # Simulate execution
        (exit, output) = call([SIMULATE, '-np', '{}'.format(num_cores), 'a.out'] 
                + SIM_FLAGS)
        self.assertTrue(exit)
    
        # Check the output against the .output file
        self.assertEqual(output.strip(), 
                read_file(path+'/'+name+'.output').strip())
    
    except Exception as e:
        sys.stderr.write('Error: {}\n'.format(e))
        raise
    
    except:
        sys.stderr.write("Unexpected error: {}\n".format(sys.exc_info()[0]))
        raise
开发者ID:xcore,项目名称:tool_sire,代码行数:27,代码来源:tests.py

示例6: render

	def render(self):
		path = self.model["filename"]
		filename = os.path.basename(path)

		self.headers["Content-Disposition"] = "inline; filename=%s" % (filename)

		return util.read_file(path)
开发者ID:20centaurifux,项目名称:meat-a,代码行数:7,代码来源:view.py

示例7: regenerate

def regenerate(in_dir):
    os.umask(022)

    global settings
    settings = util.parse_headers(util.read_file(
            os.path.join(in_dir, 'settings')).strip())

    global jinja
    jinja = jinja2.Environment(
        loader=jinja2.FileSystemLoader(os.path.join(in_dir, 'templates')),
        autoescape=True)

    posts = load_posts(os.path.join(in_dir, 'posts'))

    util.write_if_changed('index.html', generate_frontpage(posts))
    if len(posts) > FRONTPAGE_POSTS:
        util.write_if_changed('archive.html', generate_archive(posts))
    util.write_if_changed('atom.xml', generate_feed(posts))

    for post in posts:
        dir = os.path.split(post.path)[0]
        try:
            os.makedirs(dir)
        except OSError:
            pass
        root = '../' * post.path.count('/')
        util.write_if_changed(post.path,
                              generate_post_page(root, post).encode('utf-8'))
开发者ID:evmar,项目名称:cms,代码行数:28,代码来源:blog.py

示例8: get_user_sim_matrix

def get_user_sim_matrix(topics):
  matrix = {}
  for i in range(60):
    path = 'user_similarity/user_sim/'+str(topics)+'_hybrid/'+str(i)+".pickle"
    matrix.update(util.read_file(path))
    print i
  return matrix
开发者ID:Tracywangsw,项目名称:recommender,代码行数:7,代码来源:recommend.py

示例9: hill_climb

def hill_climb(init_tour):
    cur_iterator = 0
    max_iterator = 100
    min_distance = 100000;

    best_tour = init_tour

    while cur_iterator < max_iterator:
        flag = False
        for newtour in swap_cities(init_tour):
            if cur_iterator > max_iterator:
                break
            cur_iterator += 1
            distance = util.get_path_distance(newtour, util.read_file())
            if distance < min_distance:
                best_tour = newtour
                min_distance = distance
                flag = True
                break
        if flag == False:
            break

        #print best_tour
        #print min_distance
        #print cur_iterator

    return best_tour, min_distance
开发者ID:xiangliy,项目名称:GeneticAlgorithm_TSP,代码行数:27,代码来源:hillclimb.py

示例10: get_tag_sim_matrix

def get_tag_sim_matrix():
  matrix = {}
  for i in range(60):
    path = 'user_similarity/user_tag_sim/genres/'+str(i)+".pickle"
    matrix.update(util.read_file(path))
    print i
  return matrix
开发者ID:Tracywangsw,项目名称:recommender,代码行数:7,代码来源:recommend.py

示例11: main

def main():
    g = u.read_file("../data/NewYorkOneWeek.txt")
    results = iterative_removing_algorithm(g,5)
    print 'done'
    for r in results:
        nx.draw_networkx(r)
        plt.show()
开发者ID:Habitats,项目名称:athens,代码行数:7,代码来源:iterative_removing_algorithm.py

示例12: download

def download(course, item):
    """
    Download announcement JSON.
    :param course: A Course object.
    :param item: {
        "close_time": 2147483647,
        "user_id": 1069689,
        "open_time": 1411654451,
        "title": "Coursera",
        "deleted": 0,
        "email_announcements": "email_sent",
        "section_id": "14",
        "order": "6",
        "item_type": "announcement",
        "__type": "announcement",
        "published": 1,
        "item_id": "39",
        "message": "Hello, everyone.",
        "uid": "announcement39",
        "id": 39,
        "icon": ""
    }
    :return: None.
    """
    path = '{}/announcement/{}.json'
    path = path.format(course.get_folder(), item['item_id'])

    util.make_folder(path, True)
    util.write_json(path, item)

    content = util.read_file(path)
    content = util.remove_coursera_bad_formats(content)

    util.write_file(path, content)
开发者ID:kq2,项目名称:Ricin,代码行数:34,代码来源:announcement.py

示例13: main

def main():
    args = process_command_line_arguments()
    util.mkdir(PATH['TIMBRADAS'])

    xml = util.read_file(args.factura)

    # Enviamos a timbrar con el PAC
    timbra_xml(xml)
    return
开发者ID:e-fector,项目名称:cfdi-test,代码行数:9,代码来源:solo_timbrar.py

示例14: test_dev

	def test_dev(self, infile, outfile):
		sent_iter = read_file(infile)
		handle = open(outfile, 'w', encoding='utf-8')
		for sent in sent_iter:
			predict_sentence = self.predict(convert_to_no_EC(sent))
			for item in predict_sentence:
				handle.write('{0}\t{1}\n'.format(item[0], item[1]))
			handle.write('\n')
		handle.close()
开发者ID:RayFong,项目名称:DepParser,代码行数:9,代码来源:ECDetection.py

示例15: load_wordlist

def load_wordlist(filename):
    """ 
    This function should return a list or set of words from the given filename.
    """
    words = set()
    for str in util.read_file(filename):
        words.add(str)

    return words
开发者ID:wuzhongdehua,项目名称:data-guided-business-intel,代码行数:9,代码来源:twitterStream.py


注:本文中的util.read_file函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。