Write BibTeX to file

This commit is contained in:
Nicolò P 2024-01-08 16:02:29 +01:00
parent 091e5399b5
commit 768278c234
6 changed files with 81 additions and 63 deletions

View File

@ -5,12 +5,12 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Txt2Bib"
mc:Ignorable="d"
Title="MainWindow" Height="718" Width="800">
<Grid Background="#FF38383E" Margin="0,0,0,-16">
Title="MainWindow" Height="744" Width="800">
<Grid Background="#FF38383E" Margin="0,0,0,-6">
<TextBox x:Name="DropArea" Text="Trascinare qui i file txt da convertire" ToolTip="Trascinare qui i file txt da convertire" HorizontalAlignment="Left" Margin="48,82,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="526" Height="437" PreviewDragEnter="DropArea_PreviewDragEnter" PreviewDragOver="DropArea_PreviewDragOver" Drop="DropArea_Drop"/>
<TextBox x:Name="Debug" VerticalScrollBarVisibility="Auto" IsEnabled="True" HorizontalAlignment="Left" Margin="48,571,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="710" Height="106" RenderTransformOrigin="0.449,1.525"/>
<Label Content="Txt2Bib" HorizontalAlignment="Center" Margin="0,10,0,0" VerticalAlignment="Top" Foreground="White" FontFamily="Eras ITC" FontSize="28"/>
<Button x:Name="GoBtn" Cursor="Hand" Content="Genera" HorizontalAlignment="Left" Margin="628,244,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.5,0.5" Height="68" Width="127" Click="GoBtn_Click" BorderBrush="{x:Null}" Foreground="White" Background="#FF474671" FontFamily="Cascadia Code" FontSize="16">
<Button x:Name="GoBtn" Cursor="Hand" Content="Genera" HorizontalAlignment="Left" Margin="631,82,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.5,0.5" Height="68" Width="127" Click="GoBtn_Click" BorderBrush="{x:Null}" Foreground="White" Background="#FF474671" FontFamily="Cascadia Code" FontSize="16">
<Button.RenderTransform>
<TransformGroup>
<ScaleTransform/>
@ -26,6 +26,11 @@
<ImageBrush ImageSource="/copy-icon.png"/>
</Button.OpacityMask>
</Button>
<Button x:Name="OpenDestFolderBtn" ToolTip="Apri cartella destinazione" Content="Button" HorizontalAlignment="Left" Margin="631,168,0,0" VerticalAlignment="Top" BorderBrush="{x:Null}" Foreground="{x:Null}" Height="26" Width="27" Cursor="Hand" Click="OpenDestFolderBtn_Click">
<Button.OpacityMask>
<ImageBrush ImageSource="/openfolder_4896.png" Stretch="Uniform"/>
</Button.OpacityMask>
</Button>
</Grid>
</Window>

View File

@ -1,17 +1,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Txt2Bib
{
@ -75,7 +68,10 @@ namespace Txt2Bib
private void GoBtn_Click(object sender, RoutedEventArgs e)
{
var txt2bib = new Text2Bib();
Debug.Text = txt2bib.Generate(DropArea.Text);
var result = txt2bib.Generate(DropArea.Text);
Debug.Text = result;
using var outputFile = new StreamWriter("output_bibtex.bib");
outputFile.Write(result);
}
private void CopyDebug_Click(object sender, RoutedEventArgs e)
@ -83,5 +79,10 @@ namespace Txt2Bib
Debug.SelectAll();
Debug.Copy();
}
private void OpenDestFolderBtn_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start("explorer.exe", Directory.GetCurrentDirectory());
}
}
}

View File

@ -21,6 +21,31 @@ namespace Txt2Bib.Records
public string Doi { get; set; } = "";
public string Url { get; set; } = "";
public string Convert(string[] entryLines)
{
var temp = entryLines[1].Split(',');
var rearrange = (string a) =>
{
a = a.Trim();
var s = a.Split(' ');
return $"{s[1]} {s[0]}";
};
Author = temp.Select(a => rearrange(a)).ToArray();
Year = ushort.Parse(entryLines[2]);
Title = entryLines[3];
Journal = entryLines[4];
Volume = entryLines[5].Split(',').Length == 2 ?
byte.Parse(entryLines[5].Split(',')[0]) :
byte.Parse(entryLines[5]);
Issue = entryLines[5].Split(',').Length == 2 ?
byte.Parse(entryLines[5].Split(',')[1]) : null;
FirstPage = ushort.Parse(entryLines[6].Split('-')[0]);
LastPage = ushort.Parse(entryLines[6].Split('-')[1]);
Doi = entryLines.Length > 7 ? entryLines[7] : "";
return ToString();
}
public override string ToString()
{
return $"@{Type}" + "{" +$"{Author[0][..5]}_{Year},\n" +
@ -51,7 +76,7 @@ namespace Txt2Bib.Records
{
return $"@{Type}" + "{" +$"{Author[0][..5]}_{Year},\n" +
$"\tauthor = \"{string.Join(" and", Author)}\",\n" +
$"\ttitle = \"{Title}\",\n" +
$"\ttitle = {{{Title}}},\n" +
$"\tpublisher = \"{Publisher}\",\n" +
$"\taddress = \"{Place}\",\n" +
$"\tyear = \"{Year}\",\n" +

View File

@ -3,23 +3,19 @@ using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls.Primitives;
using System.Windows;
using Txt2Bib.Records;
using System.ComponentModel.DataAnnotations;
using System.Windows;
using System.Runtime.CompilerServices;
using System.CodeDom;
namespace Txt2Bib
{
internal class Text2Bib
/// <summary>
/// Converting entries from text file to BibTeX format
/// </summary>
public class Text2Bib
{
private readonly Dictionary<string, string> _citTypes = new()
{
{ "J" , "article" },
{ "B", "book" },
{ "P", "conference" },
{ "C" , "inbook" }
};
private string[] _citTypes = { "J", "B", "C", "P", "?" };
/// <summary>
/// Generate single .bib file from input text files
/// </summary>
@ -39,10 +35,15 @@ namespace Txt2Bib
result += Encoding.Latin1.GetString(contentBytes);
}
var entries = result.Split('%').ToList<string>().Select(entry =>
IEnumerable<string> entries = new List<string>();
try
{
return Process(entry);
});
entries = result.Split('%').ToList().Select(entry => Process(entry));
}
catch (Exception)
{
throw;
}
foreach (var entry in entries)
{
@ -51,56 +52,40 @@ namespace Txt2Bib
return output;
}
private string Process(string entryFromTxt)
/// <summary>
/// Creates a bib entry from source text
/// </summary>
/// <remarks>Handle exception</remarks>
/// <param name="entryFromTxt"></param>
/// <returns></returns>
/// <exception cref="Exception">Invalid citation type for this entry</exception>
public string Process(string entryFromTxt)
{
var lines = entryFromTxt.Trim().Replace("\r", string.Empty).Split("\n");
var type = lines.First();
var type = lines.First().Trim();
System.Diagnostics.Debug.WriteLine($"Entry: {entryFromTxt}; Prima riga: {type}");
if (!IsValidEntry(type)) throw new Exception($"Invalid entry type '{type}'");
string citation = type switch
{
"J" => ConvertArticle(lines),
"J" => (new ArticleBib()).Convert(lines),
//"B" => new BookBib(),
//"C" => new ChapterBib(),
//"P" => new ConferenceBib(),
_ => ConvertArticle(lines),
_ => (new ArticleBib()).Convert(lines)
};
return citation;
}
private static string ConvertArticle(string[] entryLines)
/// <summary>
/// Validate txt entry based
/// on citation types
/// </summary>
/// <param name="entry"></param>
protected bool IsValidEntry(string entryType)
{
var temp = entryLines[1].Split(',');
var rearrange = (string a) =>
{
a = a.Trim();
var s = a.Split(' ');
return $"{s[1]} {s[0]}";
};
var authors = temp.Select(a => rearrange(a)).ToArray();
var article = new ArticleBib
{
Author = authors,
Year = ushort.Parse(entryLines[2]),
Title = entryLines[3],
Journal = entryLines[4],
// TODO split with ',' for issue
Volume = entryLines[5].Split(',').Length == 2 ?
byte.Parse(entryLines[5].Split(',')[0]) :
byte.Parse(entryLines[5]),
Issue = entryLines[5].Split(',').Length == 2 ?
byte.Parse(entryLines[5].Split(',')[1]) : null,
FirstPage = ushort.Parse(entryLines[6].Split('-')[0]),
LastPage = ushort.Parse(entryLines[6].Split('-')[1]),
Doi = entryLines.Length > 7 ? entryLines[7] : "",
};
return article.ToString();
return _citTypes.Contains(entryType);
}
/// <summary>
/// TODO: How to determine correct encoding of text file??
/// </summary>

View File

@ -9,10 +9,12 @@
<ItemGroup>
<None Remove="copy-icon.png" />
<None Remove="openfolder_4896.png" />
</ItemGroup>
<ItemGroup>
<Resource Include="copy-icon.png" />
<Resource Include="openfolder_4896.png" />
</ItemGroup>
</Project>

BIN
openfolder_4896.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB