本文整理汇总了Python中bibtexparser.bwriter.BibTexWriter.write方法的典型用法代码示例。如果您正苦于以下问题:Python BibTexWriter.write方法的具体用法?Python BibTexWriter.write怎么用?Python BibTexWriter.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bibtexparser.bwriter.BibTexWriter
的用法示例。
在下文中一共展示了BibTexWriter.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: format_paper_citation_dict
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
def format_paper_citation_dict(citation, indent=' '):
"""
Format a citation dict for a paper or a list of papers into a BibTeX
record string.
:param citation: A ``Paper`` citation dict or list of such dicts.
:param indent: Indentation to be used in BibTeX output.
"""
if isinstance(citation, dict):
entries = [citation]
else:
entries = citation
# Handle conflicting ids for entries
entries_ids = collections.defaultdict(lambda: 0)
for entry in entries:
entry_id = entry['ID']
entries_ids[entry_id] += 1
if entries_ids[entry_id] > 1:
entry['ID'] = '%s_%s' % (entry_id, entries_ids[entry_id])
writer = BibTexWriter()
writer.indent = indent
with io.StringIO('') as bibfile:
db = BibDatabase()
db.entries = entries
bibfile.write(writer.write(db))
return bibfile.getvalue().strip()
示例2: exif_pdf
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
def exif_pdf(self, filename):
fields = ["Author", "Year", "Journal", "Title", "Publisher",
"Page", "Address", "Annote", "Booktitle", "Chapter",
"Crossred", "Edition", "Editor", "HowPublished",
"Institution", "Month", "Note", "Number",
"Organization", "Pages", "School",
"Series", "Type", "Url", "Volume", "Doi", "File"]
op=pexif.get_json(filename)
try:
new_op = {
field: str(value) for field in fields
for key, value in op[0].items() if field.lower() in key.lower()
}
if 'Author' not in new_op:
new_op['Author'] = 'Unknown'
id_auth=new_op["Author"].split()[-1]
id_tit = (new_op["Title"].split()[:2])
id_tit.append(id_auth)
id_val = "_".join(id_tit)
new_op["ID"] = str(id_val)
new_op["ENTRYTYPE"] = "article"
op[0] = new_op
db = BibDatabase()
db.entries = op
writer = BibTexWriter()
pdf_buff = (writer.write(db))
self.create_textview(pdf_buff)
except:
self.Messages.on_error_clicked("Can't extract data from this pdf file", "Try other methods")
示例3: persist
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
def persist(self):
if self.__bib:
self.__bib.entries[0]['note'] = self.note
self.__bib.entries[0]['tags'] = ';'.join(self.tags)
writer = BibTexWriter()
with open(self.__bib_file_path, 'w') as bibfile:
bibtex = writer.write(self.__bib)
bibfile.write(bibtex)
示例4: test_trailing_comma
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
def test_trailing_comma(self):
with io.open(_data_path('article.bib'), 'r') as bibfile:
bib = BibTexParser(bibfile.read())
with io.open(_data_path('article_trailing_comma_output.bib'), 'r') as bibfile:
expected = bibfile.read()
writer = BibTexWriter()
writer.add_trailing_comma = True
result = writer.write(bib)
self.maxDiff = None
self.assertEqual(expected, result)
示例5: test_comma_first
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
def test_comma_first(self):
with io.open(_data_path('book.bib'), 'r') as bibfile:
bib = BibTexParser(bibfile.read())
with io.open(_data_path('book_comma_first.bib'), 'r') as bibfile:
expected = bibfile.read()
writer = BibTexWriter()
writer.indent = ' '
writer.comma_first = True
result = writer.write(bib)
self.maxDiff = None
self.assertEqual(expected, result)
示例6: parsing_write
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
def parsing_write(self, filename):
# print(self.booklist)
datalist = []
writer = BibTexWriter()
writer.indent = ' '
for ref in self.TreeView.full_list:
# print(type(ref))
datadict = dict((k, v) for k, v in
zip(self.entries, ref) if v is not None)
datalist.append(datadict)
self.db.entries = datalist
with open(filename, 'w') as bibfile:
bibfile.write(writer.write(self.db))
示例7: bibtex
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
def bibtex(self,simplified=False):
if not self.__bib:
return None
from copy import deepcopy
bib = deepcopy(self.__bib)
if 'note' in bib.entries[0].keys():
del bib.entries[0]['note']
if 'tags' in bib.entries[0].keys():
del bib.entries[0]['tags']
if simplified:
for k in ['doi','acmid','isbn', 'url','link']:
if k in bib.entries[0].keys():
del bib.entries[0][k]
writer = BibTexWriter()
return writer.write(bib).strip()
示例8: report_results_to_user
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
def report_results_to_user(self):
'''
write database to self.args.output_path and inform user
'''
writer = BibTexWriter()
with open(self.args.output_path,'w') as outfile:
outfile.write(writer.write(self.args.bibtex_database))
print()
print('Finished crawling the ACL anthology!')
print('%s bibtex files were found' % self.total_found)
print('%s bibtex files were added ' % self.total_added)
print('You ran the program with the following settings:')
print()
print('overwrite',self.args.overwrite)
print('queries:',self.args.queries)
print()
print('the output file can be found at: %s' % self.args.output_path)
示例9: main
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
def main():
if len(sys.argv) < 3:
print("Wrong number of arguments. Usage: \n")
print("python3 dump_db.py name.db dump.bib")
print("Dump database")
print("Database: ", sys.argv[1])
engine = create_engine('sqlite:///app.db')
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
db = BibDatabase()
db.entries = []
dbentries = session.query(BiblioEntry)
for e in dbentries:
db.entries.append(
{'journal': e.journal,
'title': e.title,
'year': str(e.year),
'publisher': e.publisher,
'school': e.school,
'ID': e.ID,
'url': e.url,
'author': e.authors,
'keyword': e.keywords,
'ENTRYTYPE': e.ENTRYTYPE}
)
print("Write file on", sys.argv[2])
writer = BibTexWriter()
with open(sys.argv[2], 'w') as bibfile:
bibfile.write(writer.write(db))
session.close()
print("Connection closed.")
示例10: write_bib
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
def write_bib(db, order=False):
"""
Write bibtex string.
Args:
db (BibDatabase): database object to dump..
order (bool): whether to reorder entries upon writing.
Returns:
The dumped string.
"""
# Custom writer
writer = BibTexWriter()
writer.indent = '\t'
writer.order_entries_by = None
# Replace month by numeric value
for entry in db.entries:
if 'month' in entry and entry['month'] in MONTHS:
entry['month'] = '{:02d}'.format(MONTHS.index(entry['month']) + 1)
if order:
# Manual sort
order_entries_by = ('year', 'author', 'ID')
sort_entries(db, order_entries_by)
if not config.use_utf8_characters:
db.entries = [nomenclature.encode_ascii_latex(entry) for entry in db.entries]
if config.protect_uppercase:
for entry in db.entries:
entry["title"] = latex.protect_uppercase(entry["title"])
# Write bib string
return writer.write(db)
示例11: open
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
record['error'] = 'tag'
# record = c.type(record)
# record = c.author(record)
# record = c.editor(record)
# record = c.journal(record)
# record = c.keyword(record)
# record = c.link(record)
# record = c.doi(record)
# record['p_authors'] = []
# if 'author' in record:
# record['p_authors'] = [c.splitname(x, False) for x in record['author']]
return record
parser.customization = custom
with open(args.target, 'r') as f:
logging.info("Loading bibtex")
db = b.load(f, parser)
logging.info("Bibtex loaded")
#Get errors and write them out:
errored = [x for x in db.entries if 'error' in x]
with open('{}.errors'.format(args.output), 'w') as f:
f.write("\n".join(["{} : {}".format(x['ID'], x['error']) for x in errored]))
writer = BibTexWriter()
with open(args.output,'w') as f:
f.write(writer.write(db))
示例12: int
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
mon1 = dateobj.strftime("%b")
dateobj = datetime.date(2000, int(m.group(2)), 1)
mon2 = dateobj.strftime("%b")
bib_obj["month"] = ", %s-%s" % (mon1, mon2)
month = int(m.group(1))
else:
m = re.match("^[0-9]+$", month)
if m:
dateobj = datetime.date(2000, int(month), 1)
mon = dateobj.strftime("%b")
bib_obj["month"] = mon
month = int(month)
if conf_kwd is not None:
bib_id = "%s%s%s%s" % (author_kwd, conf_kwd, year, title_kwd)
else:
bib_id = "%s%s%s" % (author_kwd, year, title_kwd)
if bib_id in id_dict:
raise
id_dict[bib_id] = True
bib_obj["ID"] = bib_id
print bib_id
db.entries.append(bib_obj)
writer = BibTexWriter()
with open("seokhwankim.bib", "w") as bibfile:
bibfile.write(writer.write(db))
示例13: open
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
# record = c.keyword(record)
# record = c.link(record)
# record = c.doi(record)
record['tags'] = [i.strip() for i in re.split(',|;', record["tags"].replace("\n",""))]
# record['p_authors'] = []
# if 'author' in record:
# record['p_authors'] = [c.splitname(x, False) for x in record['author']]
return record
parser.customization = custom
with open(args.target, 'r') as f:
logging.info("Loading bibtex")
db = b.load(f, parser)
#go through entries, creating a new db for each tag, and year, and author
db_dict = {}
for entry in db.entries:
for tag in entry['tags']:
if tag not in db_dict:
db_dict[tag] = BibDatabase()
db_dict[tag].entries.append(entry)
logging.info("Writing Bibtex")
writer = BibTexWriter()
for k,v in db_dict.items():
with open(join(args.output, "{}.bib".format(k)),'w') as f:
f.write(writer.write(v))
示例14: add_raw_bibtex
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
def add_raw_bibtex(contents):
parser = BibTexParser()
bib = bibtexparser.loads(contents, parser=parser)
writer = BibTexWriter()
for i in bib.entries:
print writer.write(i)
示例15: formatText
# 需要导入模块: from bibtexparser.bwriter import BibTexWriter [as 别名]
# 或者: from bibtexparser.bwriter.BibTexWriter import write [as 别名]
def formatText(self):
if self.BibtexfilePath != '':
self.openfile()
else:
self.readcontent()
m = self.getMap()
m['IEEE Global Communications Conference'] = m['IEEE Global Communications Conference, incorporating the Global Internet Symposium']
del m['IEEE Global Communications Conference, incorporating the Global Internet Symposium']
print m
length = 0
nb = {}
for bibtex in self.allbibtex:
for key in bibtex.keys():
if len(key) > length and key != 'ENTRYTYPE':
length = len(key)
for k, v in bibtex.items():
if k == 'ENTRYTYPE' or k == 'ID':
nb[k] = v
continue
elif k == 'ID':
nb[k] = v
continue
elif k == 'doi' or k == 'ISSN' or k == 'keywords':
continue
elif v == '':
continue
elif 'url' in k:
continue
nk = k + (length - len(k)) * ' '
if 'booktitle' in nk:
if '(' in v:
v1 = v.split('(')[1].split(')')[0]
nb[nk] = 'Proc. of ' + v1
continue
flag = 0 # 未更改booktitle
to_remove = "~`[email protected]#$%^&*(){}[];':<>|-=_+"
table = {ord(char): None for char in to_remove}
clean_v = v.translate(table)
#clean_v = v.translate(string.punctuation)
#print clean_v
for kk, vv in m.items():
if kk in clean_v:
nb[nk] = 'Proc. of ' + vv[0]
publish = 'publish' + (length - 7) * ' '
nb[publish] = vv[1]
flag = 1
break
if flag == 0:
nb[nk] = v
print v
continue
elif nk.strip() == 'title' and 'booktitle' not in nk:
self.tilte = v
nv = v.split(' ')
for i in range(len(nv)):
# 标题除介词和冠词外,首字母大写
if nv[i] in self.prep or nv[i] in self.artie:
continue
# 首字母大写
else:
if 97 <= ord(nv[i][0]) <= 122:
nv[i] = chr(ord(nv[i][0])-32)+nv[i][1:]
v = ' '.join(nv)
nb[nk] = '{' + v + '}'
continue
elif 'pages' in nk:
if '--' in v:
nb[nk] = v
continue
nb[nk] = v.replace('-', '--')
continue
elif 'author' in nk:
if '\n' in v:
nb[nk] = v.replace('\n', ' ')
continue
# 其他不做改变
nb[nk] = v
db = BibDatabase()
db.entries = [nb]
writer = BibTexWriter()
writer.indent = '\t' # indent entries with 4 spaces instead of one
writer.comma_first = False # place the comma at the beginning of the line
with open(self.tilte+'.bib', 'wb') as bibfile:
bibfile.write(writer.write(db))