-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti.py
More file actions
218 lines (179 loc) · 8.34 KB
/
Copy pathmulti.py
File metadata and controls
218 lines (179 loc) · 8.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import re
import requests
import os
def format_publication_html(input_text):
"""
Formatiert eine Publikationsangabe ins HTML-Format, gleicht Daten mit CrossRef ab
und gibt die HTML-formatierte Publikation zurück.
"""
# 1. Parsen des Input-Strings (flexiblere Zerlegung)
try:
# Entferne führende Whitespaces und teile in Zeilen
lines = [line.strip() for line in input_text.strip().split('\n') if line.strip()]
if len(lines) < 3:
return f"<li><strong>Fehler:</strong> Zu wenige Zeilen in der Publikation: {len(lines)}</li>"
# Suche nach DOI in allen Zeilen
doi = None
doi_line = ""
for line in lines:
doi_match = re.search(r'DOI:\s*(.*)', line, re.IGNORECASE)
if doi_match:
doi = doi_match.group(1).strip()
# Bereinige DOI-Format
doi = doi.replace('doi.org/', '').replace('DOI.org/', '').replace('doi:', '').replace('DOI:', '').strip()
doi_line = line
break
if not doi:
return f"<li><strong>Fehler:</strong> DOI nicht gefunden in: {input_text[:100]}...</li>"
# Erste Zeile sind normalerweise die Autoren
authors_line = lines[0]
# Letzte Zeile vor DOI ist normalerweise Journal-Info, davor der Titel
doi_line_index = next((i for i, line in enumerate(lines) if 'DOI:' in line.upper()), len(lines)-1)
if doi_line_index >= 2:
title_lines = lines[1:doi_line_index-1] if doi_line_index > 2 else [lines[1]]
journal_line = lines[doi_line_index-1] if doi_line_index > 1 else ""
else:
title_lines = [lines[1]] if len(lines) > 1 else [""]
journal_line = lines[2] if len(lines) > 2 else ""
title_line = " ".join(title_lines).strip()
except Exception as e:
return f"<li><strong>Fehler beim initialen Parsen:</strong> {e}</li>"
# 2. Abrufen der Daten von CrossRef API
headers = {
'Accept': 'application/json'
}
url = f"https://api.crossref.org/works/{doi}"
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
message = data.get('message', {})
except requests.exceptions.HTTPError as http_err:
return f"<li><strong>Fehler:</strong> DOI {doi} nicht gefunden oder API-Problem (HTTP {http_err.response.status_code}).</li>"
except requests.exceptions.RequestException as req_err:
return f"<li><strong>Fehler:</strong> Netzwerkproblem beim Abrufen von DOI {doi}: {req_err}</li>"
except ValueError:
return f"<li><strong>Fehler:</strong> Ungültige JSON-Antwort für DOI {doi}.</li>"
# 3. Extrahieren und Formatieren der Daten aus der CrossRef-Antwort
try:
# Autoren
authors_list = []
if 'author' in message and message['author']:
for author_data in message['author']:
name_parts = []
if 'given' in author_data:
name_parts.append(author_data['given'])
if 'family' in author_data:
name_parts.append(author_data['family'])
authors_list.append(" ".join(name_parts))
formatted_authors = ", ".join(authors_list)
# Titel
title_value = ""
if 'title' in message and message['title']:
title_value = message['title'][0] if isinstance(message['title'], list) else message['title']
# Journal, Volume, Pages, Year
journal_name = ""
if 'container-title' in message and message['container-title']:
journal_name = message['container-title'][0] if isinstance(message['container-title'], list) else message['container-title']
volume = message.get('volume', '')
pages = message.get('page', '')
year = ""
if 'published-print' in message and 'date-parts' in message['published-print']:
year = str(message['published-print']['date-parts'][0][0])
elif 'published-online' in message and 'date-parts' in message['published-online']:
year = str(message['published-online']['date-parts'][0][0])
elif 'created' in message and 'date-parts' in message['created']:
year = str(message['created']['date-parts'][0][0])
# Zusammenbau der Journal-Zeile
journal_details_parts = []
if journal_name:
journal_details_parts.append(journal_name)
if volume:
journal_details_parts.append(f"vol. {volume}")
if year:
journal_details_parts.append(year)
if pages:
journal_details_parts.append(f"pp. {pages}")
journal_citation = ", ".join(journal_details_parts)
if journal_citation:
journal_citation += "."
# DOI Link
doi_full_url = f"https://doi.org/{doi}"
# 4. Erstellen des HTML-Outputs als Listenelement
html_output = f"""<li>
{formatted_authors}<br>
<strong>{title_value}</strong><br>
{journal_citation}<br>
DOI: <a href="{doi_full_url}" target="_blank">{doi}</a>
</li>
<br>
"""
return html_output
except KeyError as ke:
return f"<li><strong>Fehler:</strong> Erwartetes Feld '{ke}' nicht in CrossRef-Daten für DOI {doi} gefunden.</li>"
except Exception as e:
return f"<li><strong>Unbekannter Fehler beim Verarbeiten der CrossRef-Daten für DOI {doi}:</strong> {e}</li>"
def process_publications_file(input_file, output_file):
"""
Liest eine Datei mit Publikationen ein und erstellt eine HTML-Datei mit formatierter Liste.
"""
if not os.path.exists(input_file):
print(f"Fehler: Eingabedatei '{input_file}' nicht gefunden.")
return
try:
with open(input_file, 'r', encoding='utf-8') as f:
content = f.read()
# Teile den Inhalt in einzelne Publikationen durch Leerzeilen
publications = []
# Splitte bei mehreren aufeinanderfolgenden Leerzeilen oder einzelnen Leerzeilen
publication_blocks = re.split(r'\n\s*\n', content)
for block in publication_blocks:
block = block.strip()
if block: # Ignoriere leere Blöcke
publications.append(block)
if not publications:
print("Keine Publikationen in der Eingabedatei gefunden.")
return
# HTML-Header und Liste beginnen
html_content = """<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Formatierte Publikationen</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
ul { list-style-type: none; padding: 0; }
li { margin-bottom: 30px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
a { color: #0066cc; text-decoration: none; }
a:hover { text-decoration: underline; }
</style>
</head>
<body>
<h1>Publikationsliste</h1>
<ul>
"""
print(f"Verarbeite {len(publications)} Publikation(en)...")
# Verarbeite jede Publikation
for i, publication in enumerate(publications, 1):
print(f"Verarbeite Publikation {i}/{len(publications)}...")
formatted_pub = format_publication_html(publication)
html_content += formatted_pub
# HTML-Footer
html_content += """ </ul>
</body>
</html>"""
# Schreibe HTML-Datei
with open(output_file, 'w', encoding='utf-8') as f:
f.write(html_content)
print(f"HTML-Datei erfolgreich erstellt: {output_file}")
except Exception as e:
print(f"Fehler beim Verarbeiten: {e}")
# --- Hauptausführung ---
if __name__ == "__main__":
input_filename = "publikationen.txt"
output_filename = "publikationen_formatiert.html"
if os.path.exists(input_filename):
process_publications_file(input_filename, output_filename)
else:
print(f"Datei '{input_filename}' nicht gefunden.")