Skip to content

Commit 808da9b

Browse files
author
Gerit Wagner
committed
wos translator: year format
1 parent 31cbd0d commit 808da9b

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

search_query/wos/translator.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#!/usr/bin/env python3
22
"""WOS query translator."""
3+
import re
4+
35
from search_query.constants import Fields
46
from search_query.constants import Operators
57
from search_query.query import Query
@@ -116,6 +118,24 @@ def _translate_search_fields(cls, query: Query) -> None:
116118
for child in query.children:
117119
cls._translate_search_fields(child)
118120

121+
@classmethod
122+
def _format_year(cls, query: Query) -> None:
123+
"""Format year search fields to WOS syntax."""
124+
125+
if query.is_term() and query.search_field and query.search_field.value == "PY=":
126+
if re.fullmatch(r"^\d{4}$", query.value):
127+
pass
128+
129+
match = re.search(r"\d{4}", query.value)
130+
if match:
131+
query.value = match.group(0)
132+
return
133+
134+
raise ValueError(f"Invalid year format: {query.value}")
135+
136+
for child in query.children:
137+
cls._format_year(child)
138+
119139
@classmethod
120140
def to_specific_syntax(cls, query: Query) -> Query:
121141
"""Convert the query to a specific syntax."""
@@ -126,5 +146,6 @@ def to_specific_syntax(cls, query: Query) -> Query:
126146
cls.move_fields_to_operator(query)
127147
cls._remove_contradicting_search_fields(query)
128148
cls._remove_redundant_terms(query)
149+
cls._format_year(query)
129150

130151
return query

test/test_query_translation.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,3 +212,16 @@ def test_translation_pubmed_to_generic() -> None:
212212
expected = "AND[quantum[title], dot[title], spin[title]]"
213213

214214
assert converted_query == expected
215+
216+
217+
def test_translation_pubmed_date_to_wos_year() -> None:
218+
query_str = '("quantum"[ti]) AND (2022/05/01[dp])'
219+
query = search_query.parser.parse(
220+
query_str,
221+
platform=PLATFORM.PUBMED.value,
222+
)
223+
translated_query = query.translate(PLATFORM.WOS.value)
224+
converted_query = translated_query.to_string()
225+
226+
expected = 'TI="quantum" AND PY=2022'
227+
assert converted_query == expected

0 commit comments

Comments
 (0)